Via G. Falcone 5, Pollenza (MC), Italy
+39 0733 203595

PHP tip: array_diff an array of objects

That’s tricky! Let’s assume we have two arrays like these:

Looking at these few lines I would expect that those two arrays are different but if we compare them with php array_diff function they’re the same:

This happens because array_diff compares array elements as string so it calls the __toString method implicity and the string rappresentation of those objects is the same.

When you need to compare two arrays of objects is better to use array_udiff function which let you define a custom function to perform the difference.

I hope I spared you some minutes and a little headache.

Related Posts

Leave a reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.