Compare two PHP arrays by key

What is the fastest way to compare if keys from two arrays are equal?

eg,

array1: array2: 'abc' => 46, 'abc' => 46, 'def' => 134, 'def' => 134, 'xyz' => 34, 'xyz' => 34, 

in this case the result should be TRUE (same keys)

and

 array1: array2: 'abc' => 46, 'abc' => 46, 'def' => 134, 'def' => 134, 'qwe' => 34, 'xyz' => 34, 'xyz' => 34, 

the result should be FALSE (some keys are different)

array_diff_key () returns an empty array ...

+4
source share
3 answers

Use array_diff_key for what it is intended. As you said, it returns an empty array; this is what he should do.

Given array_diff_key($array1, $array2) , it will return an empty array if all keys of array1 exist in array2. To make sure the arrays are equal, you need to make sure that all keys of array2 exist in array1. If any of the calls returns a non-empty array, you know that your array keys are not equal:

 function keys_are_equal($array1, $array2) { return !array_diff_key($array1, $array2) && !array_diff_key($array2, $array1); } 
+14
source

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

OR

Use array_diff_key directly.

+4
source

How about using === instead? Do 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 ) ); 
+3
source

All Articles