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.

Matteo Moretti
Matteo Moretti
Articoli: 30

Lascia una risposta

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.