使用Array和substr的PHP随机数生成器

时间:2013-08-17 21:58:25

标签: php

我正在尝试为自己的娱乐建立一个简单的彩票号码生成器。我必须选择1和1之间的六个数字。 49,显然没有重复。

我已经尝试将mt_rand功能用于六个不同的变量,然后按顺序回显它们,但我想有可能重复数字。所以现在我正努力让以下工作。

<?php 
$randomString = substr(shuffle("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49"), 0, 6); echo $randomString; 
?>

我知道substr用于字符串而不是数组,但我找不到替代方法。

有人有解决方案吗?

5 个答案:

答案 0 :(得分:4)

您可以使用array_slice从数组中获取6个数字:

<?php
$numbers = range(1, 49);
shuffle($numbers);
$numbers = array_slice($numbers, 0, 6);
print_r($numbers);
?>

答案 1 :(得分:1)

array_rand基本上是为此设计的,但请记住它会返回,而不是值。

所以试试这个:

$numbers = array_rand(array_flip(range(1,49)),6);
var_dump($numbers);

答案 2 :(得分:1)

更好的做法是从1到49获得6个不同的随机数

numbers = array();
for(i=1;i<=6;i++){
    do{
        pick = rand(1,49);
    }while (in_array(pick, numbers));
    numbers[] = pick;
}

答案 3 :(得分:1)

这可以使用range()shuffle()函数在下面的代码中实现。


function num_rand($min, $max, $val) {
   $range = range($min, $max);
   shuffle($range);
   $result = array_slice($range, 0, $val);

      foreach($result as $number) {
         $number_string .= $number . ', ';
      }

   return rtrim($number_string, ', ');
}


echo num_rand('1', '49', '6');

答案 4 :(得分:0)

您还可以随机输入6个数字并检查是否没有这样的重复:

<?php
srand();
$TOTAL = 6;
$MAX = 46;
$MIN = 1;

$numbers = array();
for($i = 0; $i < $TOTAL; $i++) {
do {
    $new_number = rand($MIN,$MAX);
}
while(in_array($new_number, $numbers));

echo $new_number . "<br>";
}
?>

对我而言,这是最直接的解决方案,但我不知道它是否是最好的解决方案。