Home > Article > Backend Development > Detailed explanation of array_push(), array_pop() and array_shift() function usage examples in php
What are the respective usages of php array functions array_push(), array_pop() and array_shift()?
php array_push function adds one or more elements (push) to the end of the array of the first parameter, and then returns the length of the new array. array_pop() function Deletes the last element in the array. array_shift() function Deletes the
th element in the array and returns the value of the deleted element. This article will introduce these three functions to you respectively, hoping to help you learn array functions.
array_push function
array_push() function adds one or more elements (push) to the end of the array of the first parameter, and then returns the length of the new array. array_push() will issue a warning if the first argument is not an array.
Example 1
Use the array_push() function to insert new elements to the end of the array. The code is as follows
<?php $a=array("Dog","Cat"); array_push($a,"Horse","Bird"); print_r($a); ?>
Code output result:
array_pop() function
array_pop() function deletes the last element in the array. If the array is empty, or not an array, NULL will be returned.
Example 2
Use the array_pop() function to delete the last element in the array, the code is as follows
<?php $a=array("red","green","blue"); array_pop($a); print_r($a); ?>
Code output result:
array_shift() function
array_shift() function deletes the first element in the array and returns the value of the deleted element. Returns NULL if the array is empty.
Example 3
array_shift() function deletes the first element (red) in the array and returns the value of the deleted element. The code is as follows
<?php $a=array("a"=>"red","b"=>"green","c"=>"blue"); echo array_shift($a)."<br/>"; print_r ($a); ?>
Code output result:
[Related article recommendations]
Definition of php array function array_push() And usage
php array_pop() function deletes the last element in the array Example detailed explanation
Detailed explanation php array_shift() function: deletes the last element in the array First element
The above is the detailed content of Detailed explanation of array_push(), array_pop() and array_shift() function usage examples in php. For more information, please follow other related articles on the PHP Chinese website!