PHP: remove all fcn without acting as expected, Code Inside

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 doesn't work perfectly, here are some ins and outs

$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

      

Note that there are still 7 in my output. Also, the My function will only remove numbers from the array. Let me know if you notice anything, 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)));
}

      

+2


a source to share


3 answers


I would go with



return array_diff($array, array($elem));

      

+8


a source


function remall($array, $elem) {
    foreach($array as $k => $v)
        if($v == $elem)
            unset($array[$k]);
    return $array;
}

      



+1


a source


Can you guarantee that the input array is numeric (not associative) and without "holes" in the keys?

You might want to use foreach ($array as $key => $value) { ... }

instead of for ($i=0; $i < count($array); $i++) { ... }

.

Aside from the caveat described in the first paragraph, the second approach (the one you are using now) evaluates count()

each iteration for

- and unset()

will naturally change this value (first your array has ten elements, then after the first match it will have nine, etc. .).

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

Edit . The best solution (most readable and most maintainable, doing exactly what you want) would be to use , according to Flavius ​​Stef : array_diff()

return array_diff($array, array($elem));

      

0


a source







All Articles