array_slice
Take a segment from the array
array_slice()
function takes out a segment of value in the array according to the conditions and returns it.
Note: If the array has a string key, the returned array will retain the key name. (See Example 4)
Starting from the third element of the array, and return the remaining elements in the array:
<?php $a = array ( "red" , "green" , "blue" , "yellow" , "brown" ) ; print_r ( array_slice ( $a , 2 ) ) ; ?>
Try it yourself
Take it from the second element of the array and return only two elements:
<?php $a = array ( "red" , "green" , "blue" , "yellow" , "brown" ) ; print_r ( array_slice ( $a , 1 , 2 ) ) ; ?>
Try it yourself
Use negative start parameters:
<?php $a = array ( "red" , "green" , "blue" , "yellow" , "brown" ) ; print_r ( array_slice ( $a , - 2 , 1 ) ) ; ?>
Try it yourself
Set the preserve parameter to true:
<?php $a = array ( "red" , "green" , "blue" , "yellow" , "brown" ) ; print_r ( array_slice ( $a , 1 , 2 , true ) ) ; ?>
Try it yourself
Process string key names and integer key names:
<?php $a = array ( "a" => "red" , "b" => "green" , "c" => "blue" , "d" => "yellow" , "e" => "brown" ) ; print_r ( array_slice ( $a , 1 , 2 ) ) ; $a = array ( "0" => "red" , "1" => "green" , "2" => "blue" , "3" => "yellow" , "4" => "brown" ) ; print_r ( array_slice ( $a , 1 , 2 ) ) ; ?>
Try it yourself