如果多个随机数全部相等则返回true

时间:2013-09-11 22:58:23

标签: php random operand

我正在研究一些随机发生器,它就像掷骰子一样,如果所有骰子返回的数字都比你赢得游戏的数量多,如果不是你再试一次。

为了获得六个骰子,我使用mt_rand函数和每个骰子分开,所以我有这个:

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

但我不知道如何为多个随机生成的数字返回操作数。

如果我会使用2个骰子,我会使用

if ( $first === $second ) 

如果第一个和第二个骰子都返回2,则返回true

但是,如果我想要回复为真,如果所有6个骰子都返回2号,我该如何使用它?

编辑: 数字2只是一个例子,如果我只需要数字2我知道如何使用数组和变量,但点是我只需要所有数字匹配,从1到6哪个无关紧要。实际上有效,但让我们看看是否可以使用数组。

2 个答案:

答案 0 :(得分:2)

使用数组让您的生活更轻松(例如$dices,索引从0到5)

只需将其置于循环中并在每次迭代时检查。如果一个骰子不是2,$allDicesSameNumber将是假的。

$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;
}

答案 1 :(得分: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';
}
相关问题