Possible Duplicate:
php compare two associative arrays
I have two PHP arrays
$arr1 = array ([0] => apple, [1] => banana);
$arr2 = array ([banana] => banana, [apple] => apple);
In my web app, I don't know what would be the order and how many elements would be in these arrays. Moreover, one array uses number as keys and for the other one, the key = the value.
How can I check that the values of $arr1 equal the values of $arr2 ?
Thanks a lot for your help
Use array_values to extract all the values of both arrays into numerically keyed arrays. Then some sorting/uniqueing to make sure everything's in the same order and an equality test.
Since they have different keys
$arr1 = array (0 => "apple", 1 => "banana");
$arr2 = array ("banana" => "banana", "apple" => "apple");
You can use array_diff
if(!array_diff($arr1, $arr2))
{
// They are the same
}
You can use array_intersect
if(count($arr1) == count(array_intersect($arr1, $arr2)))
{
// They are the same ;
}
You can use array array_filter
if(array_filter($arr2,function($var)use($arr1){return !in_array($var,$arr1);}))
{
// They are the same ;
}
You can use array_values
$arr2 = array_values($arr2);
sort($arr1);sort($arr2); //sort to make sure they are in the same position
if($arr1 === $arr2)
{
// They are the same
}