Saturday, 15 March 2014

Find an Object in an array by comparing Object->value to all Object->values in array PHP -



Find an Object in an array by comparing Object->value to all Object->values in array PHP -

so array contains objects this:

$arr = array( new card('10', 'spades'), new card('jack', 'diamonds'), new card('king', 'spades') );

now have function:

function hascard(card $card) { if (in_array($card, $arr)) homecoming true; homecoming false; }

now above not work since need compare ($card->rank == $arr[$x]->rank) each element in $arr without looping. there function on php allows modify compareto method of array_search?

i'd suggest using array_filter here. (note: create sure $arr available within hascard function)

function hascard(card $card) { $inarray = array_filter($arr, function($x) use($card){ homecoming $x->rank === $card->rank; }); homecoming count($inarray) > 0; }

demo: https://eval.in/166460

php arrays object

1 comment: