1

Is there an easier way to do so?

$array = array(1,57,5,84,21,8,4,2,8,3,4);
$remove = 21;   
$i = 0;
foreach ($array as $value ){
    if( $value == $remove)
        unset($array[$i])
        $i++;
    }

//array: 1,57,5,84,8,4,2,8,3,4
1

3 Answers 3

10

The array_search answer is good. You could also arraydiff like this

$array = array(1,57,5,84,21,8,4,2,8,3,4);
$remove = array(21);
$result = array_diff($array, $remove); 
Sign up to request clarification or add additional context in comments.

2 Comments

Doh, I thought of the same answer as yours.
I think this is the most elegant solution.
5

If you want to delete the first occurrence of the item in the array, use array_search to find the index of the item in the array rather than rolling your own loop.

$array = array(1,57,5,84,21,8,4,2,8,3,4);
$remove = 21;

$index = array_search($remove, $array);

if (index !== false)
  unset($array[$index]);

To remove all duplicates, rerun the search/delete so long as it finds a match:

while (false !== ($index = array_search($remove, $array))) {
  unset($array[$index]);
}

or find all keys for matching values and remove them:

foreach (array_keys($array, $remove) as $key) {
  unset($array[$key]);
}

2 Comments

This is assuming the value in only in the array once. Otherwise, you can use array_keys (with the 2nd parameter).
This will only work for the first match what about duplicates?
0

This is a little cleaner:

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

UPDATE

Alternatively, you can place the non-matching values into a temp array, then reset the original.

$temp = array();

foreach($array as $key => $value) {
    if ($value != $remove) {
        $temp[$key] = $value;
    }
}
$array = $temp;

3 Comments

That's assuming it's only in there once.
This is no better than the solution proposed in the question. You should never roll your own loop when built-in functionality will do the job for you. In particular when PHP provides a built-in function for doing something, you should never duplicate that functionality with a hand-rolled loop. array_search is orders of magnitude faster than foreach.
@meagar that explains the lack of up-votes :-/ I realize it's not as efficient as array_search and array_diff, which is why I up-voted your and Mike's answers. Cheers!

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.