How does in_array check if an object is in an array of objects?

yellottyellott picture yellottyellott · Jul 31, 2012 · Viewed 13.4k times · Source

Does in_array() do object comparison where it checks that all attributes are the same? What if $obj1 === $obj2, will it just do pointer comparison instead?

I'm using an ORM, so I'd rather loop over the objects testing if $obj1->getId() is already in the array if it does object comparison. If not, in_array is much more concise.

Answer

DaveRandom picture DaveRandom · Jul 31, 2012

in_array() does loose comparisons ($a == $b) unless you pass TRUE to the third argument, in which case it does strict comparisons ($a === $b).

Semantically, in_array($obj, $arr) is identical to this:

foreach ($arr as &$member) {
  if ($member == $obj) {
    return TRUE;
  }
}
return FALSE;

...and in_array($obj, $arr, TRUE) is identical to this:

foreach ($arr as &$member) {
  if ($member === $obj) {
    return TRUE;
  }
}
return FALSE;

...and to quote the manual on what this actually checks:

When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.

On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.