Skip to content


Find differences in both arrays with PHP

Sometimes something looks easy, but it turns out to be a rabbit hole. Take for example the function array_diff in PHP. I thought it would return all the differences in both arrays, but it doesn’t. After going through the function comments thread, I came across a great solution. It’s to the point and it works!

To get the differences in both arrays, you can use:
array_merge(array_diff($array1, $array2),array_diff($array2, $array1));

For example:

$array1 = array('John', 'B', 'Smith');
$array2 = array('John', 'C', 'Smith');

$result = array_merge(array_diff($array1, $array2),array_diff($array2, $array1));

print_r($result);

will return:

Array
(
[0] => B
[1] => C
)

Basically the first call to array_diff returns the differences in $array1 and then the second call returns the differences in $array2. After that, they are merged together as an array, to provide all the differences in both arrays. Simple and sweet.

Credit goes to this comment.

Posted in PHP.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.