Home > Article > Backend Development > How to delete an array record in php
PHP is a very popular web programming language that can easily operate arrays. PHP array is a very useful data type for storing multiple values. Sometimes, we need to remove one or more elements from an array. In this article, we will discuss how to delete a record in an array in PHP.
PHP provides many built-in functions to operate on arrays. You can use these functions to add, modify or delete array elements. When deleting array elements, PHP provides two built-in functions: unset() and array_splice(). Both functions can be used to delete a single element or multiple elements from an array. Among them, the unset() function is used to delete a single element, and the array_splice() function is used to delete multiple elements.
Delete a single element
Use the unset() function to delete a single array element. An example is as follows:
$arr = array("apple", "banana", "cherry"); unset($arr[1]); // 删除第二个元素 print_r($arr);
The output result of the above code is:
Array ( [0] => apple [2] => cherry )
As can be seen from the result, the second element "banana" in the array has been deleted. Please note that in order to keep the indexes of array elements contiguous, PHP automatically rebuilds their indexes.
Delete multiple elements
You can use the array_splice() function to delete multiple array elements. The syntax of this function is as follows:
array_splice(array,start,length,replace)
The parameter description is as follows:
The example is as follows:
$arr = array("apple", "banana", "cherry", "date", "kiwi"); array_splice($arr, 1, 2); print_r($arr);
The output result of the above code is:
Array ( [0] => apple [1] => date [2] => kiwi )
As can be seen from the result, the second and third elements in the array " banana" and "cherry" have been removed.
In this article, we discussed how to delete a record from an array using PHP built-in functions. To delete a single element, you can use the unset() function. To remove multiple elements, you can use the array_splice() function. No matter which method you use, you can easily remove one or more elements from a PHP array.
The above is the detailed content of How to delete an array record in php. For more information, please follow other related articles on the PHP Chinese website!