生成10个随机数

时间:2012-11-13 10:25:07

标签: php

我试图从一组数字中显示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,但脚本没有显示任何内容。

我哪里错了?

6 个答案:

答案 0 :(得分:3)

只需使用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 />";
}

答案 1 :(得分:3)

我会改用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 />";
  }
?>

答案 2 :(得分:1)

尝试shuffle()

$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 />";
 }

答案 3 :(得分:0)

您从$num = 2000开始循环,并在$num <= 10时停止。所以它没有执行。

答案 4 :(得分:0)

<?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 />";
 }
?>

答案 5 :(得分:0)

    $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