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  |
+----------+---------+--------+
7
  • Not clear what you want to do with or because of these duplicates Commented Dec 17, 2018 at 13:46
  • $options = ['G', 'W'];, $selectedOptions = ['P', 'G', 'W']; is result true or false ? Commented Dec 17, 2018 at 13:47
  • @Cid It's should return FALSE Commented Dec 17, 2018 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 Commented Dec 17, 2018 at 13:57
  • Are you sure @DavidWinder ? Seems the simplest route to a solution Commented Dec 17, 2018 at 13:58

1 Answer 1

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";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Sort is a good idea, I was en route to post an answer with array_count_values() when Riggs closed the question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.