When you start coding, you will undoubtedly need to learn how to use arrays efficiently. Typically, you must first delete arrays by their keys.
You may also need to delete components based on their values. Let’s look at how to delete entries from an array in PHP by value.
Solution #1
PHP provides us with an awesome method that allows us to search our array for a key with a given value. This is the array search method.
It’s worth noting that this function will only identify and remove the first occurrence of the value in your array. If you need to remove several instances of the value, see Solution #2.
$array = array("foo" => "bar", "hello" => "world");
if (($key = array_search('bar', $array)) !== false) {
unset($array[$key]);
}
If the array search method detects a value, it returns its key; otherwise, it returns false. The returned key, which was populated within the if expression, will then be unset from the array.
Solution #2
If we wish to eliminate several instances from the array, we must alter our technique somewhat. We’ll utilize another technique called array keys for this approach.
$array = array("foo" => "bar", "hello" => "world", "cash" => "bar");
foreach (array_keys($array, 'bar', true) as $key) {
unset($array[$key]);
}
The array keys method in this code returns an array of keys to us.
The method’s second parameter is the value we’re looking for, and the third allows rigorous search, which means that numbers and strings with the same value are not treated the same. We then cycle through this array of keys, unsetting each one.
That’s all there is to it. You now understand how to delete entries from an array in PHP by value. Have fun coding!