Home > Article > Backend Development > The definition and usage of array_slice function in php
This article mainly introduces the definition and usage of the array_slice function in php. Interested friends can refer to it. I hope it will be helpful to everyone.
Let me tell you the basic syntax first:
array_slice ( array $array , int $offset [, int $length [, bool $preserve_keys ]] )
array_slice() returns a sequence in the array specified by the offset and length parameters.
If offset is non-negative, the sequence will start at this offset in array. If offset is negative, the sequence will start this far from the end in the array.
If length is given and positive, there will be this many cells in the sequence. If length is given and negative, the sequence will terminate this far from the end of the array. If omitted, the sequence will start at offset and go to the end of array.
Note that array_slice() will reset the keys of the array by default. As of PHP 5.0.2, this behavior can be changed by setting preserve_keys to TRUE.
$input = array("a", "b", "c", "d", "e"); $output = array_slice($input, ); //返回下标开始的数组 returns "c", "d", and "e" $output = array_slice($input, -, ); // returns "d" $output = array_slice($input, , ); // returns "a", "b", and "c" // note the differences in the array keys print_r(array_slice($input, , -)); print_r(array_slice($input, , -, true));
If you need to return a few random pieces of data, you can first use shuffle($input); to scramble the original array, and then use array_slice to obtain it
PS: PHP array_slice() function
Definition and usage
array_slice() function removes a segment of value from the array based on conditions and returns it.
Note: If the array has string keys, the returned array will retain the key names. (See Example 4)
Syntax
The code is as follows:
array_slice(array,offset,length,preserve)
Parameters |
describe |
array |
##Required. Specifies the input array. |
##offset |
Required. numerical value. Specifies the starting position of the element to be retrieved. If it is a positive number, it will be taken from the front to the back. If it is a negative value, it will be taken from the back to the front. offset Absolute value. |
length |
## Optional. numerical value. Specifies the length of the returned array. If length is positive, return that number of elements. If length is negative, the sequence will terminate this far from the end of the array. If omitted, the sequence will start at offset and continue until array The end of . |
##preserve |
Optional. Possible values: ·true - reserved key ·false - Default - Reset key |
The above is the detailed content of The definition and usage of array_slice function in php. For more information, please follow other related articles on the PHP Chinese website!