I can't seem to figure out what magic is happening behind the PHP scene and why array_unique cannot detect my duplicates.
In my specific situation, I have 2 collections of users, which I am merging into one and then keeping only unique entries. For that I am converting both collections into arrays, array_merge()
them and then based on parameter apply array_unique(..., SORT_REGULAR)
so that they are compared as objects without any conversions. I realise that comparing objects is a slippery slope, but in this case it's weirder than I though.
After merge but before the uniqueness check I have this state:
As you can see, items 4 and 11 are the same User entity (both non-strict and strict comparison agree on that). Yet after array_unique()
they both remain in the list for some reason:
As you can see, items 7-10 were detected and removed, but 11 wasn't.
How is that possible? What am I not seeing here?
Currently running PHP 7.4.5
Code is from project using Symfony 4.4.7 and Doctrine ORM 2.7.2 (although I think this should be irrelevant, if the objects are equal both by ==
and ===
comparisons).
Fun fact for bonus points - applying array_unique
twice in a row gives actually unique results:
Mind = blown
UPDATE: I have added throw new \RuntimeException()
in my User::__toString()
method, to be extra sure noone is doing conversion to string.
Please do not suggest converting to string - that is neither a solution to my problem, nor what this question is about.