If you just need to know if two arrays' values are exactly the same (regardless of keys and order), then instead of using array_diff, this is a simple method:
<?php
function identical_values( $arrayA , $arrayB ) {
sort( $arrayA );
sort( $arrayB );
return $arrayA == $arrayB;
}
$array1 = array( "red" , "green" , "blue" );
$array2 = array( "green" , "red" , "blue" );
$array3 = array( "red" , "green" , "blue" , "yellow" );
$array4 = array( "red" , "yellow" , "blue" );
$array5 = array( "x" => "red" , "y" => "green" , "z" => "blue" );
identical_values( $array1 , $array2 ); identical_values( $array1 , $array3 ); identical_values( $array1 , $array4 ); identical_values( $array1 , $array5 ); ?>
The function returns true only if the two arrays contain the same number of values and each value in one array has an exact duplicate in the other array. Everything else will return false.
my alternative method for evaluating if two arrays contain (all) identical values:
<?php
sort($a); $sort(b); return $a == $b;
?>
may be slightly faster (10-20%) than this array_diff method:
<?php
return ( count( $a ) == count( $b ) && !array_diff( $a , $b ) ? true : false );
?>
but only when the two arrays contain the same number of values and then only in some cases. Otherwise the latter method will be radically faster due to the use of a count() test before the array_diff().
Also, if the two arrays contain a different number of values, then which method is faster will depend on whether both arrays need to be sorted or not. Two times sort() is a bit slower than one time array_diff(), but if one of the arrays have already been sorted, then you only have to sort the other array and this will be almost twice as fast as array_diff().
Basically: 2 x sort() is slower than 1 x array_diff() is slower than 1 x sort().