2012-03-22 65 views
0

我有一個字符串有很多不同的數字。我正在嘗試創建一個新的隨機數並將其添加到字符串中。繼續生成隨機數,直到一個不存在 - PHP

我需要是「如果數字在字符串中已經存在,創建一個新的隨機數,並繼續做下去,直到數創建尚不字符串中存在」幫助部分。

// $string contains all the numbers separated by a comma 
$random = rand(5, 15); 

$existing = strpos($string, $random); 

if ($existing !== false) { $random = rand(5, 15); } 

$new_string = $string.",".$random; 

我知道這是不完全正確的,因爲它只會檢查它是否存在一次。我需要它來檢查以確保字符串中不存在隨機數。我使用while循環嗎?我將如何改變這個工作正常?

非常感謝您的幫助。

+0

你需要它是一個字符串的解決方案?這使得它比需要更復雜。 – Yoshi 2012-03-22 15:43:31

+0

我已經簡化它在這裏發佈,但字符串包含一個mysql行的值。 – JROB 2012-03-22 15:48:44

+0

「蘭特(5,15)」是一個例子還是隨機數的實際範圍? – Yoshi 2012-03-22 15:55:50

回答

2

工作方式類似於Endijs ......但我想張貼:)

$string = '6,7,8'; 
$arr = explode(',', $string); 

$loop = true; 
while($loop) { 
    $randomize = rand(5, 15); 
    #var_dump($randomize); 
    $loop = in_array($randomize, $arr); 
    if (!$loop) { 
     $arr[] = $randomize; 
    } 
} 

$newString = implode(',', $arr); 
var_dump($newString); 
0

檢查字符串中的數據不是最佳解決方案。那是因爲如果你的隨機數將是'5',並且在字符串中你將有15,strpos將會找到5的保證。我會將字符串轉換爲數組並且對它進行搜索。

$a = explode(',' $your_string); 
$random = rand(5, 15); 
while (in_array($random, $a)) 
{ 
    $random = rand(5, 15);  
} 
$a[] = $random; 
$your_string = implode(',', $a); 

更新 - 只是要小心 - 如果所有可能的變量已經在字符串中,它將是無限循環。

+0

我試着讓這個例子很簡單,但字符串比這個更復雜,隨機數字實際上是一個隨機八字符的字母和數字組合,所以沒有辦法隨機字符會出現在字符串中,除非它是合法的那裏。 – JROB 2012-03-22 15:57:17