0

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?

5
  • If you insist on using plain English in your arrays, you should probably have an associated array that holds the values. You only need that plain English to show the user anyway. And you're creating a seperate step at processing time. Commented Jun 24, 2014 at 20:21
  • @durbnpoisn there are more other values associated to each Card object so no I can not really use regular arrays, I need it to be an object. Commented Jun 24, 2014 at 20:22
  • Try array_filter. You can pass that a function to compare the ranks. Commented Jun 24, 2014 at 20:23
  • @RocketHazmat Would you mind showing an example? As far as I know array_filter filters out array elements that return false Commented Jun 24, 2014 at 20:23
  • @GGio: Exactly! So, filter out elements that don't match the rank. Then check how many elements remain. If that's more than 0, then it's in the array. Commented Jun 24, 2014 at 20:26

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.