Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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...

like image 509
Alex Avatar asked Jun 06 '11 13:06

Alex


1 Answers

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);
}
like image 144
meagar Avatar answered Oct 02 '22 01:10

meagar