1

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 ?

2
  • 6
    Why can't you use array_search()? Commented May 25, 2012 at 8:06
  • Yes, there is an infinite number of complicated ways to do it, but array_search is the most straight-forward. Commented May 25, 2012 at 8:11

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

An example here would probably be worthwhile, no?
2

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

Comments

2

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; 
               }
           ); 

2 Comments

Won't it remove all occurrences of $knownValue, if it is repeating. But maybe that is the desired behavior in the question asked.
@Pushpesh - yes, it will remove all occurrences of $knownValue if there are duplicates... otherwise you need some form of mechanism to identifyu which you want to delete.... but you'd need that however you were trying to remove only one occurrence of several (even array_search() won't necessarily help you there)
0

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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.