in_array如何检查对象是否在对象数组中? [英] How does in_array check if an object is in an array of objects?

查看:347
本文介绍了in_array如何检查对象是否在对象数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

in_array()在检查所有属性是否相同的情况下进行对象比较吗? 如果$obj1 === $obj2会执行指针比较呢?

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?

我正在使用ORM,所以我宁愿遍历对象以测试$obj1->getId()是否在对象比较中是否在数组中.如果不是,则in_array更为简洁.

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.

推荐答案

进行宽松比较($a == $b),除非您将TRUE传递给第三个参数,在这种情况下,它会进行 strict 比较($a === $b)

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

在语义上,in_array($obj, $arr)与此相同:

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

...和in_array($obj, $arr, TRUE)与此相同:

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.

这篇关于in_array如何检查对象是否在对象数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆