In the previous article, we introduced the method of deleting the first element or the last element in the array. If you are interested, you can click on the link to view → "PHP Array Learning: How to Remove the First and Last Elements 》. This time we continue to introduce deleting array elements and show you how to delete any element of the array.
Most of the time, the elements that need to be deleted are not fixed. They are not necessarily the beginning or end of the array, nor do they necessarily delete only one. This makes it impossible to use the array_shift() and array_pop() functions. So how can we delete any element in the array? Let’s find out today.
We previously introduced the array_splice() function in "PHP Array Learning Skillful Use of Functions to Insert Elements (2)". It is a powerful function with multiple functions: it can be inserted Array elements can be replaced, and of course array elements can be deleted (after all, the job of the array_splice() function is to delete the specified element and replace it with other values). Let’s take a look at its deletion function.
Let’s look at a small example below.
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(10,12,20,25,24); echo "原数组:"; var_dump($arr); echo "删除后的数组:" ; array_splice($arr,2); var_dump($arr); ?>
The output result is:
It can be seen that we use array_splice($arr,2)
from the $arr array Elements are deleted starting from the 3rd element, and a total of 3 elements are deleted (all elements starting from the 3rd element are deleted). array_splice($arr,$start)
will delete all elements starting from the $start position.
The $start parameter has three values:
is a positive number, then start from the $start position and delete later;
-start from the end of $arr Start by deleting from the back to the front. For example -2 means start from the second to last element of the array.
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(10,12,20,25,24); echo "原数组:"; var_dump($arr); echo "删除后的数组:" ; array_splice($arr,-2); var_dump($arr); ?>
$length parameter (the third parameter) to the function, which is used to specify the
number of elements to be deleted.
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(10,12,20,25,24); echo "原数组:"; var_dump($arr); echo "删除后的数组:" ; array_splice($arr,2,1); var_dump($arr); ?>
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(10,12,20,25,24); echo "原数组:"; var_dump($arr); echo "删除后的数组:" ; array_splice($arr,2,-1); var_dump($arr); ?>
$lengthThe parameter can also be 0, which means no To delete an element, you can combine it with the fourth parameter $value of the function to perform an insertion operation (I will not give a detailed introduction here).
PHP function array array function video explanation, come and learn!
The above is the detailed content of PHP array learning how to remove any element. For more information, please follow other related articles on the PHP Chinese website!