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

寵の児 提交于 2019-11-29 06:02:50

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.

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

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