Reputation: 7653
So my array contains objects like this:
$arr = array(
new Card('10', 'Spades'),
new Card('Jack', 'Diamonds'),
new Card('King', 'Spades')
);
Now I have a function:
function hasCard(Card $card) {
if (in_array($card, $arr)) return true;
return false;
}
Now above does not really work since I need to compare ($card->rank == $arr[$x]->rank)
for each element in that $arr
without looping. Is there a function on PHP that allows you to modify the compareTo method of array_search?
Upvotes: 0
Views: 93
Reputation: 227270
I'd suggest using array_filter
here. (Note: make sure $arr
is available inside the hasCard
function)
function hasCard(Card $card) {
$inArray = array_filter($arr, function($x) use($card){
return $x->rank === $card->rank;
});
return count($inArray) > 0;
}
DEMO: https://eval.in/166460
Upvotes: 3
Reputation: 431
The $arr
variable is not going to be available within the function hasCard
, unless you pass it as a parameter.
To answer your question, look at array_filter. This will get you a callable function in which you can pass the $arr
and $card
as parameters.
Upvotes: 1