Archive for October, 2010

PHP array_diff Quick Tip

Posted in PHP, Programming on October 19th, 2010 by Jason – 3 Comments

When using array_diff in php be sure to remember that this is a one way comparison. While this is not news, it is an easily overlooked part of the documentation for array_diff. It took me a few minutes the other day to figure out why my code was not working.

What this means? If you have {a, b, c} in array1, and {c, d, e} in array2, than array_diff(array1, array2) would produce a third array with the values {a, b} and not {a, b, d, e}. If instead you are needing to get the second set, so all the values that are not in both, there are a few options. This was my solution, though I am sure there are better ways out there.

$diff1 = array_diff($array1, $array2);
$diff2 = array_diff($array2, $array1);
$final = array_merge($diff1, $diff2);