PHP array_slice() Function

The array_slice() function returns selected parts of an array.

If the array has string keys, the returned array will always preserve the keys.

Syntax

array_slice(array,start,length,preserve)

array: Required. Specifies an array

start: Required. Numeric value. Specifies where the function will start the slice. 0 = the first element, -1 = the last element.

length: Optional. Numeric value. Specifies the length of the returned array.

preserve : Optional. Specifies if the function should preserve or reset the keys. Possible values are true, false.

<?php
// Preserve parameter set to true:
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,true));

// Preserve parameter set to false (default):
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,1,2,false));

// Note the differences in the array keys
?>

Output:

Array ( [1] => green [2] => blue )
Array ( [0] => green [1] => blue )

1 thought on “PHP array_slice() Function”

  1. I was just searching for this info for a while. After six hours of continuous Googleing, finally I got it in your site. I wonder what’s the lack of Google strategy that don’t rank this kind of informative websites in top of the list. Normally the top sites are full of garbage.

Leave a Comment

Your email address will not be published. Required fields are marked *