Usage of array_slice function in php: [array_slice($array,$start,$length,$preserve)]. The array_slice function is used to remove a segment of values from an array based on conditions and return the selected portion of the array.
array_slice() is a built-in function of PHP. The syntax is array_slice($array,$start,$length,$preserve), which is used to select according to user selection. (Condition) Gets a part of the array and returns it.
(Recommended tutorial: php video tutorial)
How to use the php array_slice() function?
php The array_slice() function takes out a value from the array based on conditions and returns it.
Basic syntax:
array_slice($array,$start,$length,$preserve)
Parameters: This function can take four parameters
● $array: required, not allowed Omit. Specifies an array.
● $start: Required and cannot be omitted. Value, specifies the starting position of the element to be taken out, 0 = first element. If the value is set to a positive number, start from front to back; if the value is set to a negative number, start from back to front. -2 means start from the second to last element of the array.
● $length: optional and can be omitted. A numerical value that specifies the length of the returned array. If the value is set to an integer, this number of elements is returned; if the value is set to a negative number, the function will terminate fetching this far from the end of the array; if the value is not set, the function returns starting from the position set by the start parameter. All elements up to the end of the array.
● $preserve: Optional, can be omitted. Specifies whether the function retains key names or resets key names. Possible values: true - keep key names, false - default (reset key names).
Return value: array_slice() function will return a selected segment of the array. If the array has string keys, the returned array will retain the key names.
Let’s take a look at how to use the php array_slice() function through an example.
Example 1:
<?php header("content-type:text/html;charset=utf-8"); $class=array("西门","灭绝","无忌","peter"); print_r(array_slice($class,0,2)); ?>
Output:
Array ( [0] => 西门 [1] => 灭绝 )
Example 2:
<?php header("content-type:text/html;charset=utf-8"); $a=array("灭绝","西门","无忌","欧阳克","韦小宝"); print_r(array_slice($a,1,2,true)); ?>
Output:
Array ( [1] => 西门 [2] => 无忌 )
Related recommendations: php array (Array function) processing
The above is the detailed content of How to use array_slice function in php. For more information, please follow other related articles on the PHP Chinese website!