PHP array_diff Quick Tip
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);
$final = array_intersect($array1, $array2);
Bob, that will give you what values are common to both arrays, but in this case the problem was to know only the values that were not in both arrays. The inverse of array_intersect.
Thanks for this tip, it helped me realize what a bit of code I was working on was actually doing.
You can use the fact that the order of $array1 and $array2 matters to tell what kind of change may have been made to an array. In my case, it was comparing an array of user-selected keywords with those already associated with an entry.
So, if $existing_keywords is the list of keywords already associated with something and $posted_keywords is the list of keywords selected by a user, then the order you use the arrays in when calling array_diff() tells you what was added or removed:
// select only the elements from $posted_keywords which
// aren’t already in $existing_keywords – i.e. added stuff
$added_keywords = array_diff($posted_keywords,$existing_keywords);
// select only the elements from $existing_keywords which
// aren’t in $posted_keywords – i.e. removed stuff
$removed_keywords = array_diff($existing_keywords,$posted_keywords);
// and, if needed, an array of everything either added or removed
$changed_keywords = array_merge($added_keywords,$posted_keywords);