PHP array_slice() Function

PHP has a built – in function, array_slice() , that you can use to extract a range of elements from an array. To use it, pass it the array to extract the slice from, followed by the position of the first element in the range (counting from zero), followed by the number of elements to extract.

Note: If the array have string keys, the returned array will always preserve the keys

Parameter Description
array Required. Specifies an array
start Required. Numeric value. Specifies where the function will start the slice. 0 = the first element. If this value is set to a negative number, the function will start slicing that far from the last element. -2 means start at the second last element of the array.
length Optional. Numeric value. Specifies the length of the returned array. If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter.
preserve Optional. Specifies if the function should preserve or reset the keys. Possible values:

  • true –  Preserve keys
  • false – Default. Reset keys

Syntax

 array_slice(array,start,length,preserve) 

Example

$a=array("Prince","Alex","James","Lachlan","Samuel");
print_r(array_slice($a,2));

Output

Array ( [0] => James [1] => Lachlan [2] => Samuel ) 

More Example

$a=array("Prince","Alex","James","Lachlan","Samuel");
print_r(array_slice($a,1,2));

Output

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

Leave a Reply

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