views:

272

answers:

1

PHP has an in_array function for checking if a particular value exists in an native array/collection. I'm looking for an equivalent function/method for ArrayObject, but none of the methods appear to duplicate this functionality.

I know I could cast the ArrayObject as an (array) and use it in in_array. I also know I could manually iterate over the ArrayObject and look for the value. Neither seems like the "right" way to do this.

"No" is a perfectly appropriate answer if you can back it up with evidence.

+2  A: 

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

If encapsulation is your goal, you can make your own subclass of 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.

Peter Bailey