In this tutorial we will see How To Delete Array Elements By Value in PHP. We can use array_search() and unset() functions or array_diff() function or array_keys() function for this purpose.
Table of Contents
We have listed three simple methods to delete array elements by value in PHP.
Using array_search() function and unset()
We can simply use array_search() function and unset() to delete array elements by value.
array_search() function
The array_search() function searches an array for a value and it returns the key for that value.
unset() function
unset() destroys or deletes the specified variable.
In first method, array_search() function will look for a specified value and it will return it's key using which unset() function will delete the value.
Take a look at the code given below.
<?php
if (($key = array_search($value, $array)) !== false) {
unset($array[$key]);
}
?>
Strict comparison !== is used in the code.
$value variable will be deleted from the array.
Using array_diff() function
We can also use simple array_diff() function to delete array element of an array.
array_diff() function
array_diff() function compares values of two arrays and it returns the difference.
This will also remove the specified value from the array if present.
See the example below.
<?php
$newArray =array_diff( [781, 301, 98, 1242], [1242] );
print_r($newArray);
?>
Note: This method is a bit slow and it creates the new array.
Using array_keys() function
array_keys() function can also be used to delete array element.
array_keys() function
array_keys() function returns an array containing the keys.
We have to define the 'value' whose key we need along side the second parameter which in this case is 'true'.
Take a look at the code given below.
<?php
foreach (array_keys($array, 1242, true) as $key) {
unset($array[$key]);
}
?>
In above code the array_keys() function will look for the defined value inside the array and it will return it's key.
This key is then used to delete the value.