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


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.