20個の乱数を生成する関数があります。
function randomAttempts()
{
$i=1;
while($i<=20)
{
echo "The number is " . rand(1,100) . "<br>";
$i++;
}
}
しかし、私の質問は、たとえば「10番目」の乱数や「11番目」などをエコーするにはどうすればよいですか?
私はここで論理が欠けていると思います。
20個の乱数を生成する関数があります。
function randomAttempts()
{
$i=1;
while($i<=20)
{
echo "The number is " . rand(1,100) . "<br>";
$i++;
}
}
しかし、私の質問は、たとえば「10番目」の乱数や「11番目」などをエコーするにはどうすればよいですか?
私はここで論理が欠けていると思います。
最も簡単な解決策は次のとおりです。
function randomAttempts()
{
$i=1;
$printIndex = 11;
while($i<=20)
{
if ($i == $printIndex)
echo "The number is " . rand(1,100) . "<br>";
$i++;
}
}
または、 $printIndex をパラメーターとして関数に渡すことができます
編集: 11 番目と言う必要がある場合、20 の数字を生成する意味はありません。そのようなコードはよりうまく機能します:
function randomAttempts($printIndex = 1)
{
$i = 1;
$random = 0;
while($i<=$printIndex )
{
$random = rand(1,100);
$i++;
}
echo "The number is " . $random . "<br>";
}
function randomAttempts($num)
{
$i=1;
$ar=array();
while($i<=$num)
{
$ar[]=rand(1,100);
$i++;
}
$out=array_pop($ar);
unset($ar);
return $out;
}
サンプル
echo randomAttempts(10);
echo randomAttempts(11);
function randomAttempts($passNthNumberToBeEchoed)
{
$i=1;
while($i<=20)
{
$randNum = rand(1,100);
if($passNthNumberToBeEchoed==$i){
echo "The number is " . $randNum . "<br>";
}
$i++;
}
}
それが役に立てば幸い。