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) {

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) {

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!



Related articles

OnePlus 5T Wallpapers Download

Introduction: The OnePlus 5T is a popular smartphone known for...

Airtel’s First Quarterly Loss in 2002: A Closer Look at Jio’s Impact

The telecom industry has witnessed several significant shifts over...

Xiaomi Confirms Investment in Blackshark Gaming Phone Launch set for April 13

An engaging introduction to Xiaomi Confirms Investment in Blackshark...

LG G7 ThinQ M LCD Panel

Introduction:The LG G7 ThinQ M LCD panel is a...

Intel Core i9 Laptops with Optane Memory

Intel Core i9 laptops with Optane Memory combine the...

Apple iOS 11.4 Beta 1

Apple iOS 11.4 Beta 1 is the latest update...

Google Search AI Reorganization: Improving Search Quality and User Experience

Introduction:In the ever-evolving digital landscape, search engines play a...
Peter Graham
Peter Graham
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.


Please enter your comment!
Please enter your name here