0

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  |
+----------+---------+--------+
dWinder
  • 11,597
  • 3
  • 24
  • 39
Paul
  • 411
  • 6
  • 15
  • Not clear what you want to do with or because of these duplicates – RiggsFolly Dec 17 '18 at 13:46
  • `$options = ['G', 'W'];`, `$selectedOptions = ['P', 'G', 'W'];` is result `true` or `false` ? – Cid Dec 17 '18 at 13:47
  • @Cid It's should return `FALSE` – Paul Dec 17 '18 at 13:48
  • 2
    @RiggsFolly This not exactly duplicate because here he doesn't want to remove them but to compare even if duplication exists – dWinder Dec 17 '18 at 13:57
  • Are you sure @DavidWinder ? Seems the simplest route to a solution – RiggsFolly Dec 17 '18 at 13:58
  • @RiggsFolly It may be good way to achieve that but it is not the same question - therefor I don't think its qualify as duplicate question. And notice the OP specify that he DO NOT want to remove the duplicate – dWinder Dec 17 '18 at 14:36
  • @DavidWinder It does now, it did not specify any such thing when I Duped the question. I have reopened it – RiggsFolly Dec 17 '18 at 14:40

1 Answers1

3

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";
}
dWinder
  • 11,597
  • 3
  • 24
  • 39
  • Sort is a good idea, I was en route to post an answer with `array_count_values()` when Riggs closed the question – Cid Dec 17 '18 at 14:04