tags:

views:

45

answers:

2

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?

+5  A: 

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 )

Galen
I think the problem with array_diff is that if a value from array2 does not exist in array1, it will actually get added, because it's doing a diff. In the array above for example, array2 includes value1, but array1 doesn't even have value1, so it can't be removed since it doesn't even exist.
Lingo
you are mistaken, array_diff doesn't add anything. try it out.
Galen
A: 

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>';
muxare