Search code examples
phpremoveall

PHP: Remove all fcn not 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 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)));
}

Solution

  • I'd go with

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