Justin John
Justin John

Reputation: 9616

How to delete an element from an array in php without array search?

Delete an element from an array in php without array_search

I want to delete an array element from array, but I dont know the array key of that element only value is known

It is possible by array_search with value, first to find the key and then use unset

Is there any inbuilt array function to remove array element with array value ?

Upvotes: 1

Views: 233

Answers (4)

nyson
nyson

Reputation: 1055

The only valid case to not use array_search is if you'd like to unset several values. You still need to use keys though. I'd recommend you to iterate through the array and remove fields that match your criteria.

foreach($array as $key => $value) {
    if($value === $deleteValue)
        unset($array[$key]);
}

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212402

Example showing one way you can do this without using array_search()

$myArray = array(5, 4, 3, 2, 1, 0, -1, -2); 
$knownValue = 3;

$myArray = array_filter(
               $myArray, 
               function($value) use ($knownValue) {
                   return $value !== $knownValue; 
               }
           ); 

Upvotes: 2

Brad
Brad

Reputation: 15879

Any function that has to "to remove array element with array value" will have to perform a loop over every* element looking for the value to delete. Therefore you might as well just add your own for loop to do this, or array_search() will do this for you.

The reason arrays have keys is so that you can get at values efficiently using that key.

*actually you'd stop looping once you'd found it rather than keep looking, unless there could be duplicates to remove

Upvotes: 2

s.webbandit
s.webbandit

Reputation: 17000

You can only remove element from array only by referencing to this KEY. So you have to get this KEY somehow. The function to get the key for the searched value from array is exactly array_search() function which returns KEY for given VALUE.

Upvotes: 4

Related Questions