0

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.

lonerunner
  • 1,282
  • 6
  • 31
  • 70
  • 1
    `$first === $second && $second === $third && $third === $fourth ...` etc – Sammitch Sep 11 '13 at 22:59
  • Learning to use arrays will make this easier, then you can use functions like [array_count_values()](http://www.php.net/manual/en/function.array-count-values.php) – Mark Baker Sep 11 '13 at 23:01

2 Answers2

2

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;
}
bwoebi
  • 23,637
  • 5
  • 58
  • 79
  • but this is when it's locked to number 2 i need to match all 6 dices with same number it doesn't matter which one. – lonerunner Sep 11 '13 at 23:28
  • Sorry for stupidity but is this gonna decrease chances of winning, it's like im rolling 7 dices now, first we generate 1 random number in $number than we need to match it with 6 other random generated numbers? – lonerunner Sep 11 '13 at 23:46
  • @AleksandarĐorđević No, you just roll 6 dices. Because I changed `$i` to start at 1 instead of zero. Look at [the diff](http://stackoverflow.com/posts/18752729/revisions). – bwoebi Sep 12 '13 at 00:04
2
$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';
}
Mark Baker
  • 209,507
  • 32
  • 346
  • 385