What's the fastest way to compare if the keys of two arrays are equal?
for eg.
array1: array2:
'abc' => 46, 'abc' => 46,
'def' => 134, 'def' => 134,
'xyz' => 34, 'xyz' => 34,
in this case result should be TRUE (same keys)
and:
array1: array2:
'abc' => 46, 'abc' => 46,
'def' => 134, 'def' => 134,
'qwe' => 34, 'xyz' => 34,
'xyz' => 34,
result should be FALSE (some keys differ)
array_diff_key() returns a empty array...
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With