2012-02-23 79 views
1

我必須從1到3得到三個隨機數,結果中沒有重複值 With:
$ total ='3';
$ rand1 = rand(1,$ total);
$ rand2 = rand(1,$ total);
$ rand3 = rand(1,$ total);
和結果前:1.2.3或3.2.1,2.1.3或
請幫助我,在此先感謝(PHP)選擇三個沒有重複值的隨機數

+0

如果範圍是1到3並且您想要3個數字,是否爲隨機?他們必須是整數嗎? – 2012-02-23 17:11:09

+0

我想打印3個數字,如:三個隨機數是3 1和2 – 2012-02-23 17:13:58

回答

1

爲什麼不嘗試:

$inp = array(1, 2, 3); 
shuffle($inp); 
$rand1 = $inp[0]; 
$rand2 = $inp[1]; 
$rand3 = $inp[2]; 
+0

謝謝但如果$ total = 1000,它是如何工作的? – 2012-02-23 17:25:16

+0

看看@AljoshaBre的答案 - 它會處理任何數量的值。 – 2012-02-23 17:29:20

6

如何洗牌陣列,像所以:

$num = range(1,$total); 
shuffle($num); 
print_r($num); 
+3

我每天都是shufflin' – 2012-02-23 17:13:05

+0

非常感謝你:) – 2012-02-23 17:35:19

0
$values = array(); 
$max_value = 10; 
$count = 5; // must be less than $max_value of you'll get an infinite while loop 
for ($i = 0; $i < $count; $i++){ 
    do { 
     $value = rand(1, $max_value); 
    } 
    while(isset($values[ $value ]) /* && count($values) < $count */) 
    $values[ $value ] = TRUE; 
} 

print_r(array_keys($values));