Jump to: navigation, search

Php array slice

From w3cyberlearnings

Contents

PHP function array_slice

This function splits array and returns part of the array accordingly.

Syntax array_slice

  • array: array input
  • start: starts position (positive number slices from the beginning, and negative number slices from the end)
  • length (optional): the length of the array return
  • preserve (optional): True (preserves key), False (not preserve key)
array_slice(array, start, length, preserve);

Example 1

<?php
$records = array('Alyssa', 'Emma', 'Landon', 'Alex', 'Christ', 'Sam', 'Mark');

$a1 = array_slice($records, 2); // Landon, Alex, Christ, Sam, Mark
$a2 = array_slice($records, 3); // Alex, Christ, Sam, Mark
$a3 = array_slice($records, -1); // Mark
$a4 = array_slice($records, -2); // Sam, Mark
$a5 = array_slice($records, 0, 2); // Alyssa, Emma
$a6 = array_slice($records, 2, 2); // Landon, Alex
$a7 = array_slice($records, -1); // Mark
$a8 = array_slice($records, 2, 3); // Landon, Alex, Christ

print_r($a1);
print_r($a2);
print_r($a3);
print_r($a4);
print_r($a5);
print_r($a6);
print_r($a7);
print_r($a8);
?>

Output

Array
(
    [0] => Landon
    [1] => Alex
    [2] => Christ
    [3] => Sam
    [4] => Mark
)
Array
(
    [0] => Alex
    [1] => Christ
    [2] => Sam
    [3] => Mark
)
Array
(
    [0] => Mark
)
Array
(
    [0] => Sam
    [1] => Mark
)
Array
(
    [0] => Alyssa
    [1] => Emma
)
Array
(
    [0] => Landon
    [1] => Alex
)
Array
(
    [0] => Mark
)
Array
(
    [0] => Landon
    [1] => Alex
    [2] => Christ
)


Example 2: array keys preserve

<?php
$records = array(
	 33 => 'Alyssa',
	 44 => 'Emma',
	 55 => 'Landon',
	 66 => 'Alex',
	 77 => 'Christ',
	 88 => 'Sam',
	 99 => 'Mark');

$a1 = array_slice($records, 2,2,true);
print_r($a1); 
?>

Output

Array
(
    [55] => Landon
    [66] => Alex
)

Example 3: array index is not preserve

<?php
$records = array(
	 33 => 'Alyssa',
	 44 => 'Emma',
	 55 => 'Landon',
	 66 => 'Alex',
	 77 => 'Christ',
	 88 => 'Sam',
	 99 => 'Mark');

$a1 = array_slice($records, 2,2,false);
print_r($a1); 
?>

Output

Array
(
    [0] => Landon
    [1] => Alex
)

Related Links


Navigation
Web
SQL
MISC
References