我正在创建一个自定义验证码,它运行良好,但有时它会从中选择一个$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]];