PHP: Compare the Keys of an Array and find the Difference Programming 27 FEB 2012

To compare two arrays to see if there is a difference, one often makes use of the array_diff function which takes two arrays, compares array1 against array2 and then returns the difference.

Now if you actually want to check for a difference in array keys (say for example you’ve built up two associative arrays of table columns and want to check one table’s structure versus another), you can make use of the array_diff_key function, which acts in a very similar fashion to array_diff except for the part where it compares the keys of the associative input arrays as opposed to the values contained within the arrays.

In practice:

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

print_r(array_diff_key($array1, $array2));

/* Results in:
array(2) { 


About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.