compare two PHP arrays by key

22,363

Solution 1

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

Solution 2

Use array_keys to get array of keys and then use array_diff.

OR

Use array_diff_key directly.

Solution 3

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 ) );
Share:
22,363
Alex
Author by

Alex

I'm still learning so I'm only here to ask questions :P

Updated on June 07, 2020

Comments

  • Alex
    Alex almost 4 years

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

  • Alex
    Alex almost 13 years
    oh that was it :D I needed to reverse the parameters on array_key_diff :) thanks
  • Alex
    Alex almost 13 years
    does this report true if both arrays have the same keys, but in different order?
  • user229044
    user229044 almost 13 years
    === is no more suitable than == for this purpose.