In PHP, array is a very common data type. In the process of using an array, it is often necessary to delete elements in it. Generally speaking, PHP provides two methods for deleting array elements: one is to delete the element at a specified index, and the other is to delete all elements.
If you need to delete all elements in the array, you can use PHP's built-in function array_splice() or unset(). The use of these two methods will be introduced below.
Use array_splice() to delete all elements
The array_splice() function is one of the built-in functions provided by PHP and can be used to slice arrays. When the slice length is 0, all elements in the array can be deleted.
The specific operation steps are as follows:
$array = array(1, 2, 3, 4, 5);
array_splice($array, 0);
The first parameter is the array to be operated on; the second parameter is the starting position to be deleted, here is 0, which means starting from the first element of the array Delete; the third parameter is the length to be deleted, here is 0, which means that the length to be deleted is the length of the array, that is, all elements are deleted.
var_dump($array);
The output result is as follows:
array(0) { }
As you can see, there are no elements in the array. .
Use unset() to delete all elements
In addition to using the array_splice() function, you can also use the unset() function to delete all elements in the array. The specific steps are as follows:
$array = array(1, 2, 3, 4, 5);
foreach ($array as $key => $value) { unset($array[$key]); }
Among them, use the foreach() function to traverse all elements in the array, and use the unset() function to delete each element.
var_dump($array);
The output result is as follows:
array(0) { }
You can also see that there is no longer anything in the array element.
Summary
In PHP, to delete all elements in an array, you can use the array_splice() function or unset() function. In actual development, you can choose the corresponding method to operate according to specific needs.
The above is the detailed content of How to delete all elements from php array. For more information, please follow other related articles on the PHP Chinese website!