Remove Elements from an Array by Value in PHP?

Share This Post

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!


Please enter your comment!
Please enter your name here

Related Posts

Get Permalink of Page Outside of The Loop in WordPress

WordPress users occasionally encounter situations where they need to...

How to find GPU Temperature in Windows 10?

Windows 10 has a plethora of diagnostic and monitoring...

How to open or create Armor sets in Runescape 3?

Making or unpacking Armor sets is a frequent way...

Why people buy Burnt Meat in RS3?

Players will occasionally approach you in the Grand Exchange...

Ironmen Feather Shops – What you need to know!

Feathers are one of the most difficult resources for...

What you need to know about Al-Kharid Archeology Money Making

Archeology, Runescape's newest talent update, has generated various AFK-friendly...
- Advertisement -spot_img