2015-01-31 130 views
0

我已經在數組中生成了6個使用rand()函數的隨機數。我想確保這些數字都不重複。 我已經寫:6個不同的隨機唯一編號php

$lucky_numbers = array (rand (1,50), rand (1,50),rand (1,50),rand (1,50),rand (1,50),rand (1,50)); 
if ($lucky_numbers[0] == $lucky_numbers[1]) { 
    print "same"; 
    $lucky_numbers[1]++; 
} 
if ($lucky_numbers[1] > 50) { 
    $lucky_numbers[1] = $lucky_numbers[1]- 6; 
} 

,然後檢查每個連續數有類似的代碼。但有些東西不起作用。有任何想法嗎 ? 在此先感謝。

+4

從1到50。然後使用'array_rand()'挑選從陣列6個隨機元素製作的陣列。 – Barmar 2015-01-31 21:29:47

+0

@Barmar:如果有重複?我需要10個唯一的1到5之間的隨機數。 – AbraCadaver 2015-01-31 21:32:41

+0

@AbraCadaver如果從1-50開始創建一個數組並將其拖動到一起,那麼您如何假設重複會存在? – Jon 2015-01-31 21:33:33

回答

0

只需使用shuffle函數。

<?php 
$numbers = range(1, 50); 
shuffle($numbers); 
for ($x=1;$x<=6;$x++){ 
    echo $numbers[$x] . "\n"; 
} 
?> 

參見codepad example

+0

你可能不想使用'array_search'來保存一些內存,因爲你並不需要大量的唯一數字,這可能會更快。 – Gal 2015-01-31 21:44:03

+0

'更快'和'save_memory'只能適用於大量數據。除非我使用「睡眠」,否則我無法使用50個按鍵。 – 2015-01-31 21:53:12

+0

也我不知道你在尋找什麼。 – 2015-01-31 21:54:18