tags:

views:

41

answers:

3

I made this simple function (remove all $elem from $array):

function remall($array, $elem) {
    for($i=0; $i < count($array); $i++)
        if($array[$i] == $elem)
            unset($array[$i]);
    $newarray = array_values($array);
    return $newarray;
}

But it isn't working perfectly, here are some inputs and outputs

$u = array(1, 7, 2, 7, 3, 7, 4, 7, 5, 7, 6, 7);
$r = remall($u, 7);
Output of $r: 12345767

$n = array(7, 7, 1, 7, 3, 4, 6, 7, 2, 3, 1, -3, 10, 11, 7, 7, 7, 2, 7);
$r = remall($n, 7);
Output of $r: 1346231-30117727

Notice how there are still 7s in my outputs. Also, My function will only be removing numbers from an array. Let me know if you spot something, thanks.

SOLUTION: Hey guys this is what worked for me (Thanks to Flavius Stef)

function remall($array, $elem) {
    return array_values(array_diff($array, array($elem)));
}
+1  A: 
function remall($array, $elem) {
    foreach($array as $k => $v)
        if($v == $elem)
            unset($array[$k]);
    return $array;
}
Mark Baker
You have a good answer, but Stef has the best answer.
Mark Tomlin
A: 

Can you guarantee the input array is numeric (rather than associative) and without 'holes' in the keys?

You may want to use foreach ($array as $key => $value) { ... } rather than for ($i=0; $i < count($array); $i++) { ... }.

Aside from the caveat described in the first paragraph, the second approach (the one you're using now) evaluates count() each iteration of for - and unset() will change that value, naturally (first your array has ten elements, then after the first match, it'll have nine, and so forth).

Another option, sidestepping the need to make your own function entirely, would be for you to use array_filter() and supply a custom callback method, though that's not a very good option if your criterium changes a lot (which, it being a parameter in your example, it looks like it would be ;) ).

Edit: The best solution (most readable and most maintainable, while doing exactly what you want) would be to use array_diff(), as per Flavius Stef's answer:

return array_diff($array, array($elem));
pinkgothic
the input will always be a array of numbers yeah
Josh K
No, I mean, a numeric array rather than an associative array, as in, that all keys in the array are numeric. Sorry, I could have been clearer with that wording. Let me fix :3
pinkgothic
ahh it wil always be numeric, by the looks of it also without holes.
Josh K
+7  A: 

I'd go with

return array_diff($array, array($elem));
Flavius Stef
+1 Dude. Yes. Simplicity for the win!
pinkgothic
That is very cool shortcut
Josh K
Nice trick because you could return array_diff($array, array(1,7)); if you wanted to remove more than one element/digit
Mark Baker