[英]Generating 10 random numbers
我正在嘗試從數字數組中顯示10個隨機數,但均未成功。
這是我的代碼:
<?php
$num = array("2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009");
//echo $num[rand(0,9)];
echo '<br/>';
for ($num = 2000; $num <= 10; $num[rand(0,9)]++)
{
echo "The number is " . $num . "<br />";
}
?>
盡管我的ubuntu php.ini上有display_errors = On
,但腳本不顯示任何內容。
我要去哪里錯了?
只需使用array_rand
:
array_rand($num, 10); // returns a new array with 10 randomly selected values.
之后,您可以使用foreach
遍歷這些:
$rand = array_rand($num, 10);
foreach($rand as $key) {
echo "The number is " . $num[key] . "<br />";
}
我會改用shuffle
功能。
<?php
$num = array("2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009");
shuffle($num);
echo '<br/>';
foreach ($num as $value)
{
echo "The number is " . $value . "<br />";
}
?>
$num= array("2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008",
"2009");
shuffle($num);
//echo $num[rand(0,9)];
echo '<br/>';
for ($i = 0; $i < count($num); $i++)
{
echo "The number is " . $num[$i] . "<br />";
}
您從$num = 2000
開始循環,並在$num <= 10
時停止。 因此它不會執行。
<?php
$num= array("2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008",
"2009");
//echo $num[rand(0,9)];
echo '<br/>';
for ($i = 0; $i < count($num); $i++)
{
echo "The number is " . $num[rand(0, count($num))] . "<br />";
}
?>
$num= array("2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009");
for($i=0; $i<10; $i++){
$rand = rand(0,count($num));
echo "The number is " . $num[$rand] . "<br />";
// unset($num[$rand]); //to get unique numbers each time .. this will unset array item after its showed
// $num = array_values($num); //reindex after unset
}
如果只想獲得唯一的結果,可以使用unset和array_values
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.