Home >Backend Development >PHP Problem >How to delete an element in an array in php
In PHP, array is a very common data type. When we need to delete an element in the array, we can use the array_splice() or unset() function to achieve this.
The array_splice() function removes elements of a specified length from an array and replaces them with another set of values. If replacement is not required, the replacement value parameter can be omitted. You can use the array_splice() function according to the following syntax:
array_splice($array, $start, $length, $replacement);
Among them, $array is the array that needs to be operated, $start is the starting position, that is, the position of the element to be deleted, $length is the number of elements to be deleted, $replacement is the element to be replaced (optional).
For example, the following code deletes the element with index 2 in the array $arr:
$arr = array('a', 'b', 'c', 'd', 'e'); array_splice($arr, 2, 1); print_r($arr);
The output result is as follows:
Array ( [0] => a [1] => b [2] => d [3] => e )
The unset() function is used to release variables or array elements. The syntax is as follows:
unset($array[$key]);
Among them, $array is the array that needs to be operated, and $key is the key name of the element that needs to be deleted.
For example, the following code deletes the element with key name 2 in array $arr:
$arr = array('a', 'b', 'c', 'd', 'e'); unset($arr[2]); print_r($arr);
The output result is as follows:
Array ( [0] => a [1] => b [3] => d [4] => e )
Summary
array_splice () function and unset() function can delete elements in the array. If you need to change the length of the array, you can use the array_splice() function. If you only need to remove elements without changing the length of the array, you can use the unset() function.
The above is the detailed content of How to delete an element in an array in php. For more information, please follow other related articles on the PHP Chinese website!