Question

Im working on some random generator, and it's something like roll a dices, if all dices are returning same numbers than you won a game if not than you try again.

To get six dices i used mt_rand function and for every dice separately, so i have this:

$first = mt_rand(1,6);
$second = mt_rand(1,6);
$third = mt_rand(1,6);
$fourth = mt_rand(1,6);
$fifth = mt_rand(1,6);
$sixth = mt_rand(1,6);

But i don't know how to return if operand for multiple random generated numbers.

If i would use like 2 dices i would just use

if ( $first === $second ) 

that would return true if first and second dices, both have returned number 2

But how do i use it if i want to echo true if all 6 dices to return number 2 ?

Edit: number 2 is just an example if i would need only number 2 i know how to do it with array and variable but point is that i need only all numbers to match, it doesn't matter which ones from 1 to 6. And first answer actually works but let's see if it's possible to do with array.

Was it helpful?

Solution

Use arrays to make your life easier (e.g. $dices with indices from 0 to 5)

Just put it in a loop and check at every iteration. If one dice isn't 2, $allDicesSameNumber wil be false.

$number = mt_rand(1, 6);
$allDicesSameNumber = true;
for ($i = 1; $i < 6 /* dices */; $i++) {
    $dices[$i] = mt_rand(1, 6);

    if ($dices[$i] !== $number)
        $allDicesSameNumber = false;
}

OTHER TIPS

$diceCount = 6;
$diceArray = array();
for($i=1; $i<=$diceCount; $i++) {
    $diceArray[] = mt_rand(1,6);
}
if (count(array_count_values($diceArray) == 1) {
    echo 'All the dice have the same number';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top