7

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.

Alana Storm
  • 164,128
  • 91
  • 395
  • 599
  • The doc you provided seems to pretty clearly indicate that there is no such method. Pedantically speaking, it's not really possible for us to strictly prove that no such function exists. The linked doc is all the proof you're going to get. – Frank Farmer Jul 30 '09 at 20:11
  • 1
    People who work on the PHP core might have more information. People who've run into the problem and submitted a bug report might have more information. PHPs OO documentation is often doesn't cover everything it could. I might have missed something obvious. Just because **you** can't answer the question doesn't mean there isn't an answer. – Alana Storm Jul 30 '09 at 20:14

1 Answers1

9

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
  • 105,256
  • 31
  • 182
  • 206