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

僤鯓⒐⒋嵵緔 提交于 2019-11-30 08:02:29

问题


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.


回答1:


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.




回答2:


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().



来源:https://stackoverflow.com/questions/11743527/how-does-in-array-check-if-an-object-is-in-an-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!