Home » Php » php – Removing all instances of items from array

php – Removing all instances of items from array

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have an array which may have duplicate values

$array1 = [value19, value16, value17, value16, value16]

I’m looking for an efficient little PHP function that could accept either an array or a string (whichever makes it easier)

$array2 = ["value1", "value16", "value17"];
or 
$string2 = "value1 value16 value17";

and removes each item in array2 or string2 from array1.

The right output for this example would be:

$array1 = [value19]

For those more experienced with PHP, is something like this available in PHP?

How to&Answers:

you’re looking for array_diff

$array1 = array('19','16','17','16','16');
$array2 = array('1','16','17');
print_r(array_diff($array1,$array2));

Array ( [0] => 19 )

Answer:

For the string version to work, use explode.
Like this:

function arraySubtract($one, $two) {
    // If string => convert to array
    $two = (is_string($two))? explode(' ',$two) : $two;
    $res = array();
    foreach (array_diff($one, $two) as $key => $val) {
        array_push($res, $val);
    }

    return $res;
}

This allso returns an array with key = 0….n with no gaps

Test with this:

echo '<pre>';
print_r(arraySubtract(array(1,2,3,4,5,6,7), array(1,3,7)));
print_r(arraySubtract(array(1,2,3,4,5,6,7), "1 3 7"));
print_r(arraySubtract(array("val1","val2","val3","val4","val5","val6"), array("val1","val3","val6")));
print_r(arraySubtract(array("val1","val2","val3","val4","val5","val6"), "val1 val3 val6"));
echo '</pre>';