In PHP, if you want to delete the first item of an array, you need to use the array_shift()
function to achieve this. This function removes the first element from the array and returns the value of that element. The following is a sample code that uses the array_shift()
function to delete the first item of the array:
$arr = array('apple', 'banana', 'orange'); $first_item = array_shift($arr); echo '删除的元素是:' . $first_item . '<br>'; echo '剩余的数组是:'; print_r($arr);
The above code will output the following:
删除的元素是:apple 剩余的数组是:Array ( [0] => banana [1] => orange )
As you can see, use array_shift()
The function successfully deletes the first item in the array and returns the value of the element. The remaining array contains only the remaining two items.
In addition to using the array_shift()
function, you can also use the unset()
keyword to delete the first item in the array. The following is a sample code that uses unset()
to delete the first item of the array:
$arr = array('apple', 'banana', 'orange'); unset($arr[0]); echo '剩余的数组是:'; print_r($arr);
The above code will output the following:
剩余的数组是:Array ( [1] => banana [2] => orange )
As you can see, use ## The #unset() keyword can also successfully delete the first item in the array. However, unlike the
array_shift() function, it does not return the value of the deleted element.
array_shift() function or the
unset() keyword. However, it should be noted that when deleting items in the array, the key values of the array will be rearranged, so it needs to be used with caution.
The above is the detailed content of How to delete the first item of an array in php. For more information, please follow other related articles on the PHP Chinese website!