Home > Article > Backend Development > How to remove the first element of an array in php
Elimination method: 1. Use array_shift() function, syntax "array_shift($arr)"; 2. Use array_splice() function, syntax "array_splice($arr,0,1)"; 3. Use "array_slice($arr,1)" statement.
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php removes the array The first element
#Method 1: Use the array_shift() function
PHP array_shift() function can delete the element at the beginning of the array
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(10,12,20,25,24); echo "原数组:"; var_dump($arr); array_shift($arr); echo "删除后的数组:" ; var_dump($arr); ?>
You can see this example. There are 5 elements in our original $arr array. After using the array_shift($arr)
method, reuse var_dump($arr)
Output the array and find that there are only 4 elements, and the head element of the array has been deleted.
array_shift($arr)
After the function deletes the first element at the beginning of the $arr array, the length of the arr array will be reduced by 1 and all other elements will be moved forward by one . If the key is numeric, all elements will get a new key, starting at 0 and increasing by 1; but string keys will remain unchanged.
And after we perform the deletion operation, we output the original array to observe whether the elements are deleted. It is not difficult to find that array_shift() will change the of the original array.
Method 2: Use array_splice() function
array_splice() function is used to delete part of the elements of the array; you can delete it directly or replace it with other values. .
Example: Delete the first element in the array
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(10,12,20,25,24); echo "原数组:"; var_dump($arr); array_splice($arr, 0,1); echo "删除后的数组:" ; var_dump($arr); ?>
Method 3: Use the array_slice() function
array_slice() function is used to intercept an array, that is, to extract a fragment from the array.
Return value: Return the intercepted subarray.
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(12,20,25,24,26); echo "原数组:"; var_dump($arr); echo "删除后的数组:" ; var_dump(array_slice($arr, 1)); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove the first element of an array in php. For more information, please follow other related articles on the PHP Chinese website!