Paul
Paul

Reputation: 421

php - Compare arrays with duplicated values

I need to compare (without remove ANY value) 2 arrays BUT each of these arrays can have duplicated values so for e.g. I have those 2 arrays:

$options = ['G', 'W'];
$selectedOptions = ['G', 'G', 'W'];

This should return FALSE. Below is my code which I have. It works good but only for unique values, how to 'upgrade' it for duplicated values?

$mergeOptions = array_merge($selectedOptions, $options);
$intersect = array_intersect($selectedOptions, $options);
$diff = array_diff($mergeOptions, $intersect);

if (count($diff) === 0) {
    // $options are 'equal' to $selectedOptions
} else {
    // $options are not 'equal' to $selectedOptions
}

More examples:

| selected | options | result |  
+----------+---------+--------+  
|  G, G, W |  G, W   |  FALSE |
+----------+---------+--------+
|   G, W   |  G, W   |  TRUE  |
+----------+---------+--------+
| G, P, W  | G, G, W |  FALSE |
+----------+---------+--------+
| G, P, G  | P, G, G |  TRUE  |
+----------+---------+--------+

Upvotes: 0

Views: 42

Answers (1)

dWinder
dWinder

Reputation: 11642

You can sort the arrays with sort and then compare them.

$a = ["P", "G", "G"];
$b = ["G", "P", "G"];
sort($a);
sort($b);

if ($a == $b) {
    echo "TRUE \n";
} else {
    echo "FALSE... \n";
}

Upvotes: 3

Related Questions