Array is a common data type in PHP. The data in the array is usually taken out directly through the key of the array, or obtained through loop traversal. How to take out a section in the array, this article will show you how to use array_slice()
The function takes out a segment from the array. First, let’s take a look at the syntax:
array_slice ( array $array , int $offset , int $length = null , bool $preserve_keys = false ) : array
$array: the input array.
$offset: Specifies the starting position of the element to be retrieved
$length: Optional, specifies the length of the returned array.
$preserve_keys: Optional, specifies whether the function retains the key name or resets the key name
Return value: Returns one of the segments. If the $offset parameter is larger than the $array size, an empty $array will be returned.
Code example:
1. There are two parameters
<?php $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,1)); ?>
输出:Array ( [0] => green[1] => blue[2] => yellow[3] => brown)
2. Three parameters
<?php $a=array("red","green","blue","yellow","brown"); print_r(array_slice($a,1,3)); ?>
输出:Array ( [0] => green[1] => blue[2] => yellow)
3. Four parameters
<?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)); ?>
输出:Array([b] => green [c] => blue) Array([0] => green[1] => blue)
Recommended: 《2021 PHP interview questions summary (collection)》《php video tutorial》
The above is the detailed content of Correct use of array_slice() function in PHP. For more information, please follow other related articles on the PHP Chinese website!