Remove Elements from an Array by Value in PHP?

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!

spot_img

Subscribe

Related articles

How to get million views on youtube?

To get a million views on YouTube, you will...

Can I create a custom dashboard in react?

Yes, you can create a custom dashboard in React....

All You Need to Know About Xbox 360 Backward Compatibility

The Xbox 360 works well with some games that...

How to Check if an Array has More than One Element in PHP?

An array is a group of data structures. In...

Learn How to Select All in VIM?

Now is the time to improve your VIM skills...
spot_img
Peter Graham
Peter Grahamhttps://fix-iphones.com
Hi there! I'm Peter, a software engineer and tech enthusiast with over 10 years of experience in the field. I have a passion for sharing my knowledge and helping others understand the latest developments in the tech world. When I'm not coding, you can find me hiking or trying out the latest gadgets.

LEAVE A REPLY

Please enter your comment!
Please enter your name here