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
Kirill Kulakov
  • 10,035
  • 9
  • 50
  • 67
  • 1
    That's one way to do it. You could also use array_splice(). See: http://stackoverflow.com/questions/369602/how-to-delete-an-element-from-an-array-in-php. – Ayush Aug 29 '12 at 19:38

3 Answers3

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); 
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
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]);
}
user229044
  • 232,980
  • 40
  • 330
  • 338
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;
Matt
  • 6,993
  • 4
  • 29
  • 50
  • That's assuming it's only in there once. – gen_Eric Aug 29 '12 at 19:40
  • 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`. – user229044 Aug 29 '12 at 20:15
  • @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! – Matt Aug 30 '12 at 13:44