Reputation: 208
I've got an array containing
"1", "2", "3", "4"
And I use array_rand
to select one of those numbers randomly five times. Then I want to count how many of the result of array_rand
that have been chosen multiple times like the number 2 got chosen 2 times and number 3 got chosen 2 times.
I have tested doing this
$array = array($kort1[$rand_kort1[0]], $kort1[$rand_kort2[0]], $kort1[$rand_kort3[0]], $kort1[$rand_kort4[0]], $kort1[$rand_kort5[0]]);
$bank = array_count_values($array);
if (in_array("2", $bank)) {
echo "You got one pair";
} elseif(in_array("2", $bank) && (???)) {
echo "You got two pair";
}
it will tell me "You got one pair" if one of those numbers were randomly chosen 2 times but my problem is I don't know how to make it say "You got two pairs" if 2 of those numbers were chosen 2 times.
the result of $bank
could be
[4] => 1 [3] => 2 [1] => 2
Upvotes: 2
Views: 90
Reputation: 5941
You can use array_filter to appy a function to each element of your array
$bank=array(4 => 1, 3 => 2, 1 => 2); // Your array
function pairs($var) {
return($var === 2); // returns value if the input integer equals 2
}
$pairs=count(array_filter($bank, "pairs")); // Apply the function to all elements of the array and get the number of times 2 was found
if ($pairs === 1)
{
echo "you got one pair";
}
if ($pairs === 2) {
echo "you got two pairs";
}
EDIT
Thought of this one liner later:
$pairs=count(array_diff($bank, array(1,3,4)));
Upvotes: 1
Reputation: 3350
Try this: (This will work even if your array has more than 4 values)
$count = 0;
foreach ($bank as $key=>$value) {
if ($value === 2) {
$count++;
}
}
if ($count) {
$s = $count > 1 ? 's' : '';
echo "You got $count pair$s";
}
It will show an output like You got 1 pair
. If you want to use words (like you mentioned in your question), you can use NumberFormatter class
Upvotes: 1