tags:

views:

51

answers:

4

How to compare 2 arrays with each other?
For example i have array("a", "b", "c") and array("a", "c", "b") It would return true when they're compared. But if one of the letters if not found in one of them it would return false. Order is not important.

+1  A: 

Well it doesnt return true, but it does the job - array_diff

realshadow
Tried it out. Didn't work as expected in my code.
Semas
@Semas, that is because array_diff only returns entities from array1 that are missing from array2. You would also need to check `array_diff($array2, $array1)` for completeness.
Brandon Horsley
+5  A: 

You need to bring the content of both arrays into the same order prior to comparison:

sort($array1);
sort($array2);
// now you can compare as usual
if ($array1 == $array2) ...

Or use asort() if you want to maintain keys.

soulmerge
+2  A: 

array_diff

$diff = array_diff($array1, $array2);
if(!count($diff)){
  # is the same
}
Haim Evgi
array_diff only returns entities from array1 that are missing from array2. You would also need to check `array_diff($array2, $array1)` for completeness. The sort solution is probably faster.
Brandon Horsley
thanks brandon, you right
Haim Evgi
A: 

You can use:

if (empty(array_diff($array1, $array2)) {
    // do something
}
Alec Smart
`empty` only works on variables.
soulmerge
This would not work anyway, array_diff only returns entities from array1 that are missing from array2. You would also need to check `array_diff($array2, $array1)` for completeness.
Brandon Horsley