PHP function introduction—array_shift(): Pop out the element at the beginning of the array
PHP is a widely used scripting language, especially suitable for web development. In PHP, many powerful array functions are provided, one of which is the array_shift() function. This function removes and returns the first element from the beginning of the array, while updating the original array's key value.
The syntax of the array_shift() function is as follows:
mixed array_shift (array &$array)
Among them, $array is the array to be operated on, which is passed by reference.
Let’s look at a specific example to show how to use the array_shift() function:
$fruits = array("apple", "banana", "orange", "grape"); $firstFruit = array_shift($fruits); echo "第一个水果是:".$firstFruit."<br>"; echo "剩余的水果有:"; print_r($fruits);
The output result is:
第一个水果是:apple 剩余的水果有:Array ( [0] => banana [1] => orange [2] => grape )
From the above example, we can It can be seen that the array_shift() function pops the first element "apple" of the array $fruits and stores it in the $firstFruit variable. Afterwards, the original array $fruits is updated, leaving only the elements "banana", "orange" and "grape".
It should be noted that the array_shift() function will not only return the value of the first element, but also update the key value of the original array. In the above example, the indexes of the original array are rearranged starting from [0].
In addition to simple arrays, the array_shift() function can also operate on associative arrays. The following is an example of an associative array:
$person = array("name" => "John", "age" => 25, "gender" => "male"); $firstProperty = array_shift($person); echo "第一个属性是:".$firstProperty."<br>"; echo "剩余的属性有:"; print_r($person);
The output is:
第一个属性是:John 剩余的属性有:Array ( [age] => 25 [gender] => male )
From the above example, we can see that the array_shift() function works in associative arrays differently from ordinary arrays same. It pops and returns the value in the first key-value pair, updating the keys in the original array.
Summary:
The array_shift() function is a very practical array function in PHP. It can easily remove and return the first element from the beginning of the array, and at the same time update the key value of the original array. Whether it is an ordinary array or an associative array, the array_shift() function can correctly handle and return the corresponding value. In actual development, we can flexibly use this function according to specific needs to make the code more concise and efficient.
The above is the detailed content of PHP function introduction—array_shift(): Pop out the elements at the beginning of the array. For more information, please follow other related articles on the PHP Chinese website!