Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 738
Alan Storm Avatar asked Jul 30 '09 19:07

Alan Storm


People also ask

What is In_array?

The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.

What is Arrayobject?

The Array Object. Arrays are data structures that store information in a set of adjacent memory addresses. In practice, this means is that you can store other variables and objects inside an array and can retrieve them from the array by referring to their position number in the array.

How do you check if an array contains a value in PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

How do you handle an array object in PHP?

Converting an object to an array with typecasting technique: php class bag { public function __construct( $item1, $item2, $item3){ $this->item1 = $item1; $this->item2 =$item2; $this->item3 = $item3; } } $myBag = new bag("Books", "Ball", "Pens"); echo "Before conversion :".


1 Answers

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.

like image 185
Peter Bailey Avatar answered Sep 18 '22 16:09

Peter Bailey