简体   繁体   English

PHP的ArrayObject是否具有in_array等价物?

[英]Does PHP's ArrayObject have an in_array equivalent?

PHP has an in_array function for checking if a particular value exists in an native array/collection. PHP有一个in_array函数,用于检查本机数组/集合中是否存在特定值。 I'm looking for an equivalent function/method for ArrayObject, but none of the methods appear to duplicate this functionality. 我正在寻找ArrayObject的等效函数/方法,但没有一个方法似乎复制此功能。

I know I could cast the ArrayObject as an (array) and use it in in_array. 我知道我可以将ArrayObject转换为(数组)并在in_array中使用它。 I also know I could manually iterate over the ArrayObject and look for the value. 我也知道我可以手动迭代ArrayObject并查找值。 Neither seems like the "right" way to do this. 这似乎都不是“正确”的方式。

"No" is a perfectly appropriate answer if you can back it up with evidence. 如果你能用证据支持,“不”是一个非常恰当的答案。

No. Even ignoring the documentation, you can see it for yourself 不。甚至无视文档,您可以自己查看

echo '<pre>';
print_r( get_class_methods( new ArrayObject() ) );
echo '</pre>';

So you are left with few choices. 所以你没有多少选择。 One option, as you say, is to cast it 正如你所说,一种选择就是施展它

$a = new ArrayObject( array( 1, 2, 3 ) );
if ( in_array( 1, (array)$a ) )
{
  // stuff
}

Which is, IMO, the best option. 这是IMO最好的选择。 You could use the getArrayCopy() method but that's probably more expensive than the casting operation, not to mention that choice would have questionable semantics. 可以使用getArrayCopy()方法,但这可能比转换操作更昂贵,更不用说选择会有可疑的语义。

If encapsulation is your goal, you can make your own subclass of ArrayObject 如果封装是您的目标,您可以创建自己的ArrayObject子类

class Whatever extends ArrayObject 
{
  public function has( $value )
  {
    return in_array( $value, (array)$this );
  }
}

$a = new Whatever( array( 1, 2, 3 ) );
if ( $a->has( 1 ) )
{
  // stuff
}

I don't recommend iteration at all, that's O(n) and just not worth it given the alternatives. 我根本不建议迭代,那是O(n)并且考虑到替代方案,它们是不值得的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM