Home > Article > Backend Development > How to delete array value in php
php is a server-side scripting language widely used in web development. In the process of developing web applications using PHP, sometimes we need to delete a certain value in an array. This article will introduce how to delete an array value in PHP.
1. Unset() function
The unset() function is a function used to destroy variables in PHP. When using the unset() function to destroy a value in the array, the value is located The memory space will be released and the key values of the array will be re-indexed.
Example:
<?php $arr=array("a","b","c","d","e"); unset($arr[1]); print_r($arr); ?>
Output result:
Array ( [0] => a [2] => c [3] => d [4] => e )
In the above example, the unset() function deletes the second element "b" in the array $arr, and the array is reset After indexing, they are "a", "c", "d" and "e".
2. array_splice() function
array_splice() function is a function in PHP that is used to delete an element in an array and replace it with other elements. It removes elements of specified length and inserts new elements into the array. If no elements are inserted, elements of the specified length are removed.
Example:
<?php $arr=array("a","b","c","d","e"); array_splice($arr,1,1); print_r($arr); ?>
Output result:
Array ( [0] => a [1] => c [2] => d [3] => e )
In the above example, the array_splice() function deletes the second element "b" in the array $arr and replaces it with Array index rearrangement.
3. array_diff() function
array_diff() function is used in PHP to compare two arrays and return the difference between the two arrays (that is, in one array but not in the other) elements in an array). You can easily delete an element in an array by constructing the element to be deleted as an array and then using the array_diff() function.
Example:
<?php $arr=array("a","b","c","d","e"); $remove = array("b"); $result = array_diff($arr, $remove); print_r($result); ?>
Output result:
Array ( [0] => a [2] => c [3] => d [4] => e )
In the above example, the element "b" to be deleted is constructed as an array $remove, and then used with the array $arr The array_diff() function finally gets the $result array, which contains all the elements that are in the array $arr but not in the array $remove, that is, the "b" element is deleted.
Summary:
The above are the three methods for deleting array values in PHP. Developers can choose the appropriate method according to specific business needs. Each of these methods is very practical and convenient, and I hope it will be helpful to PHP developers.
The above is the detailed content of How to delete array value in php. For more information, please follow other related articles on the PHP Chinese website!