2

Just a note of previous research on SO:

At least I believe that:

Given the example:

$arr1 = [21, 23, 25];
$arr2 = [25, 21, 23];

It the easiest, nondestructive manner to compare these for equal values, regardless of order

$arr1s = $arr1;
$arr2s = $arr2;

sort($arr1s, SORT_NUMERIC);
sort($arr2s, SORT_NUMERIC);

$isSameValues = ($arr1s === $arr2s);

Or is there an easier, cleaner way to do this?

2
  • 1
    See the first answer: stackoverflow.com/questions/4519847/… Commented Jun 25, 2014 at 17:06
  • 1nflktd: Not sure if you meant the answer posited in the question of the first response. I need to streamline as best I can due to the hit that this is going to take. I have no option but to be making this call a metric $&%*tonne of times. :-/ Commented Jun 25, 2014 at 19:14

2 Answers 2

4

Use array_count_values, which is O(n) vs O(n log n) for sorting

$a = [1, 1, 3, 2];
$b = [1, 2, 2, 3];
var_dump (array_count_values($b) == array_count_values($a)); //false

Note: this only works with arrays where all values are strings or ints.

Sign up to request clarification or add additional context in comments.

6 Comments

Note that something like this $a = [33];$b = [33, 3.3, 2.1]; would return true. Example: ideone.com/EytqqR
yes, but I really liked your answer, and I know that someone will see this in the future and will try to compare with floats and will complain about it, so I'm just informing already :p
@1nflktd fair enough, added a note to clarify the limitation :)
FuzzyTree: Are you saying that the array_count_values is O(n) and the double copy and sort being O(n long n)? If so, then I will try this as my lists are ALWAYS ints and should NEVER have duplicates. (Should being the operative term)
@LordAndrei each array_count_values is O(n) whereas each sort is O(n log n), to be clear array_count_values handles duplicates correctly. my note about duplicates was regarding array_diff
|
0

You were very near to the right solution! Here is your code fixed:

$arr1 = [21, 23, 25];
$arr2 = [25, 21, 23];

$arr1s = $arr1;
$arr2s = $arr2;

sort($arr1s, SORT_NUMERIC);
sort($arr2s, SORT_NUMERIC);

$isSameValues = ($arr1 == $arr2);

See it working here: http://sandbox.onlinephpfunctions.com/code/b737d3a9cf45e077a0d1f2c0195f389b81ace4a3

If the two arrays have same keys and values, a == is enough, as shown here:

enter image description here

Comments

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.