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.
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.
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.
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.
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 :".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With