0

我正在创建一个自定义验证码,它运行良好,但有时它会从中选择一个$rand_keys大于显示框数的随机数。我该如何解决?

$color = array("red", "blue", "yellow", "white", "green", "purple", "brown", "orange", "pink", "black");
$random_num_box = mt_rand(3,8);

$numbers=array(0,1,2,3,4,5,6,7,8,9);

$rand_keys = array_rand($numbers, $random_num_box);
$ran_box =  mt_rand(0, $random_num_box);

echo "Random number of boxes:  ".$random_num_box."<br /><br />";
echo "<div>";
foreach ($rand_keys as $k=>$v) {
    echo "<div style='width: 20px; height: 20px; border: 1px solid #dcdcdc; margin-right: 2px; display: inline-block; background: ".$color[$numbers[$v]].";'></div>";
}
echo "</div>";

echo "<br />What is the color of box # ". ($ran_box + 1) ."?";
echo "<br />Answer:  ".$color[$rand_keys[$ran_box]];
4

2 回答 2

3

问题是偶尔你会得到一个比显示的盒子数量大的随机选择的数字。这似乎源于以下两行:

$rand_keys = array_rand($numbers, $random_num_box);
$ran_box =  mt_rand(0, $random_num_box);

由于这很难模拟,由于是随机的,最简单的方法是想出一个例子来证明它不起作用。

从研究中,您会发现array_rand将采用一个数组并根据第二个参数随机选择项目的数量,在这种情况下为$random_num_box。所以我们有以下数组:

array(
 [0] => 1,
 [1] => 2,
 [2] => 3
)

现在我们继续得到随机答案($ran_box)。参数将是(对于这个例子)$random_num_box = 3;所以运行的命令是

$ran_box =  mt_rand(0, 3);

您将获得一个介于 0 和 3(包括)之间的值。由于您的数组的大小仅为 3 (0->2),因此当您的随机数为 3(或 )时,您将收到错误消息$random_num_box。这是由于试图访问array[3]不存在的。

要解决此问题,您必须将最大值减少 1。

$rand_keys = array_rand($numbers, $random_num_box);
$ran_box =  mt_rand(0, $random_num_box - 1);
于 2013-04-16T03:09:48.257 回答
1

我认为您只需要从中减去 1$ran_box

$ran_box =  mt_rand(0, $random_num_box-1);
于 2013-04-16T03:18:39.463 回答