Home >Backend Development >PHP Problem >How to delete an element in an array in PHP
Method: 1. In the foreach loop, find the specified element; then use unset() to delete the element. 2. Use array_search() to find the specified element, and use unset() to delete the element. 3. Use array_search() to find the element, and use array_splice() to delete the element.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Method 1: Using foreach and unset () function deletes a specified element in the array
foreach($array as $k=>$v){ if($v == 'day'){ unset($array[$k]): } }
In the foreach loop, find the array element; then use the unset() function to delete the specified array value.
Method 2: Use the array_search() and unset() functions to delete a specified element in the array
if(($key = array_search('day',$arr))){ unset($arr[$key]); }
array_search() function to find a key value in the array . If the value is found, the key of the matching element is returned. If not found, returns false.
Then use the unset() function to delete the specified array value.
Method 3: Use array_search() and array_splice() functions to delete a specified element in the array
array_splice() function can be used with the unset() function Same effect
if(($key = array_search('day',$arr))){ array_splice($arr, $key,1); }
array_splice() function removes the selected element from an array and replaces it with a new element. This function will also return the array containing the removed elements. Syntax:
array_splice(array,start,length,array)
array_splice() has four parameters:
Parameter | Description |
---|---|
array | Required. Specifies an array. |
start |
Required. numerical value. Specifies the starting position of deleted elements.
|
length |
Optional. numerical value. Specifies the number of elements to be removed, which is also the length of the returned array.
|
array |
Optional. Specifies the array with the elements to be inserted into the original array. If there is only one element, it can be set to a string and does not need to be set to an array. |
Recommended study: "PHP Video Tutorial"
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!