Michael
Michael

Reputation: 576

PHP compare 2 arrays and get only the non matching values

I have 2 arrays I want to get the values that are not the same but for some reason this is not working:

$newArray = array_unique(array_merge($array1, $array2)

var_dump(array1) = array(3) { [0]=> string(17) "verbal aggression" [1]=> string(19) "physical aggression" [2]=> string(3) "vol" }

var_dump(array2) = array(2) { [0]=> string(17) "verbal aggression" [1]=> string(19) "physical aggression" }

So I suspect $newArray to be:

array(1) { [0]=> string(3) "vol"" }

Upvotes: 0

Views: 3026

Answers (2)

kkica
kkica

Reputation: 4104

If you want the difference between two arrays you can use array_diff as suggested by @Sunil. But that finds only the elements that are in $array1 but not in $array2.

If you want to find differences use the function below. This will also find elements that are in $array2 but not in $array1

function differences($array1, $array2){
    return array_merge(array_diff($array1,$array2),array_diff($array2,$array1));
}

Upvotes: 2

Sunil Gehlot
Sunil Gehlot

Reputation: 1589

array_diff — Computes the difference of arrays

$array1 = array("verbal aggression", "physical aggression", "vol");
$array2 = array("verbal aggression", "physical aggression");

$result=array_diff($array1,$array2);
print_r($result);

Output :

Array
(
    [2] => vol
)

Upvotes: 2

Related Questions