Home > Article > Backend Development > Delete Array Elements_PHP Tutorial
It is very simple to add elements to an array in PHP. Just use assignment. The key of the array will be automatically added, but what about deleting elements in the array? Have you ever thought about it? Is it rare? I am dealing with a shopping trip recently. I encountered the problem of deleting elements in an array when I was using a basket program. After searching for a long time, I finally found a way to delete the array. It is actually very simple.
At first, I referred to an article "String Array, Deleting Array Elements" (OSO There is a method in ), using unset, but there is a flaw. For example, $a is an array:
$a=array("red", "green", "blue", "yellow"); $a=array("red", "green", "blue", "yellow");
count($a); //Get 4
unset($a[1]); //Delete the second element
count($a); //Get 3
echo $a[ 2]; //There are only three elements in the array. I wanted to get the last element, but I got blue,
echo $a[1]; //No value
?>
That is to say, deletion After the elements in the array, the number of elements in the array (obtained using count()) changed, but the array subscripts were not rearranged, and the corresponding values must be operated by deleting the keys before the array.
Later I Another method is used, which is actually not called a "method" at all. It uses the ready-made function array_splice() in PHP4.
$a=array("red", "green", "blue", "yellow" ); $a=array("red", "green", "blue", "yellow");
count ($a); //Get 4
array_splice($a,1,1); //Delete the second element
count ($a); //Get 3
echo $a[2]; //get yellow
echo $a[1]; //get blue
?>
Compare this program with the previous one, you can see that array_splice( ) not only deletes the elements, but also rearranges the elements so that there are no null values among the elements of the array (such as $a[1] in the previous example).
array_splice() is actually a function that replaces array elements. , but simply delete the element without adding a replacement value. The following is the usage of array_splice():
array array_splice (array input, int offset [, int length [, array replacement]])