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

后端 未结 2 1921
轻奢々
轻奢々 2020-12-17 16:33

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

2条回答
  •  佛祖请我去吃肉
    2020-12-17 17:24

    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.

提交回复
热议问题