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

2

15

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.

Mika answered 31/7, 2012 at 15:23 Comment(0)
B
32

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.

Bruton answered 31/7, 2012 at 15:26 Comment(1)
Awesome, thanks. There's a stupid timer, so I can't accept for another 5 mintues.Mika
R
0

Objects are always references in PHP 5+ and can only be copied (thus creating a new object) by using clone.

That means you should be able to use in_array().

Rule answered 31/7, 2012 at 15:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.