Current Location: Home> Function Categories> array_slice

array_slice

Take a segment from the array
Name:array_slice
Category:Array
Programming Language:php
One-line Description:Returns the selected part of the array.

Definition and usage

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)

Example

Example 1

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

Example 2

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

Example 3

Use negative start parameters:

 <?php
$a = array ( "red" , "green" , "blue" , ​​"yellow" , "brown" ) ;
print_r ( array_slice ( $a , - 2 , 1 ) ) ;
?>

Try it yourself

Example 4

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

Example 5

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

Similar Functions
Popular Articles