以下是我的代码的一部分:
<?php
$terning1 = rand(1,6);
$terning2 = rand(1,6);
$terning3 = rand(1,6);
$terning4 = rand(1,6);
$terning5 = rand(1,6);
$terning6 = rand(1,6);
//Here I need a system to check how many of them that gets number 6
?>
soo我需要的是检查返回数字6的$ terning1-6中有多少。让我说$ terning1和$ terning4然后我需要一种方式告诉我其中2个是6.我不# 39;我不知道如何做到这一点,因为我之前从未做过类似的事情。
答案 0 :(得分:1)
由于您为变量命名的方式,您可以使用variable variables循环遍历它们:
$sixes = 0;
for ($i = 1; $i <= 6; $i++) {
$variable = "terning$i";
if ($$variable === 6) {
$sixes++;
}
}
但是我会强烈建议使用数组来存储你的数字,并在你去的时候计算六个数字:
$terning = array();
$sixes = 0;
for($i = 1; $i <= 6; $i++){
$terning[$i] = rand(1, 6);
if ($terning[$i] === 6)
{
$sixes++;
}
}
或者事后计算:
$sixes = count(array_keys($terning, 6));
答案 1 :(得分:0)
如果您可以将所有内容存储在数组$terning
然后,
if (in_array(6,$terning )) {
//Do Something
}
答案 2 :(得分:0)
你可以在一组terning值上使用array_count_values函数,如下所示:
// Variable to determine the amount of randomly generated numbers
$amountOfTernings = 6;
$terningsArray = [];
// Storing the random numbers in an array
for($i = 0; $i < $amountOfTernings; $i++) {
$terningsArray[] = rand(1, 6);
}
// Constructs an array that counts the number of times a number has occurred
$terningOccurrences = array_count_values($terningsArray);
// Variable that stores the number of occurrences of 6
$howManySixes = isset($terningOccurrences[6]) ? $terningOccurrences[6] : 0;