compare two PHP arrays by key


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)


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);

Answered By – user229044

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published