What\'s the fastest way to compare if the keys of two arrays are equal?
for eg.
array1: array2:
\'abc\' => 46, \'abc\' => 46,
\'d
How about using === instead? You know, the operator for equality?
$array1 = array(
'abc' => 46,
'def' => 134,
'xyz' => 34
);
$array2 = array(
'abc' => 46,
'def' => 134,
'xyz' => 34,
);
var_dump( array_keys( $array1 ) === array_keys( $array2 ) );
Use array_keys to get array of keys and then use array_diff.
OR
Use array_diff_key directly.
Use array_diff_key, that is what it is for. As you said, it returns an empty array; that is what it is supposed to do.
Given array_diff_key($array1, $array2)
, it will return an empty array if all of array1's keys exist in array2. To make sure that the arrays are equal, you then need to make sure all of array2's keys exist in array1. If either call returns a non-empty array, you know your array keys aren't equal:
function keys_are_equal($array1, $array2) {
return !array_diff_key($array1, $array2) && !array_diff_key($array2, $array1);
}