2

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 
4
  • 1
    Is [3] => 2 [1] => 3 considered two pairs? Commented Dec 8, 2017 at 3:15
  • @Erwin [3] => 2 [1] => 2 thats two pairs and the code should ignore the last number Commented Dec 8, 2017 at 3:24
  • How bout four of a kind? Is that also considered two pairs? e.g. [3] => 4 [1] => 1 Commented Dec 8, 2017 at 3:27
  • Updated my answer with a one line solution Commented Dec 8, 2017 at 22:15

2 Answers 2

1

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

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

Comments

1

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)));

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.