I have a string with a lot of different numbers. I am trying to create a new random number and add it to the string.
The part I need help with is "if the number already exists in the string, create a new random number, and keep doing it until a number is created that does not yet exist in the string".
// $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;
I know this isn't quite right as it will only check if it's existing once. I need it to keep checking to make sure the random number does not exist in the string. Do I use a while loop? How would I change this to work properly?
Your help is much appreciated.
A solution that works like Endijs ... but I want to post that :)
$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);
Checking data in string is not the best solution. Thats because if your random number will be '5', and in string you will have 15, strpos will find accurance of 5. I would convert string to array and do search on it.
$a = explode(',' $your_string);
$random = rand(5, 15);
while (in_array($random, $a))
{
$random = rand(5, 15);
}
$a[] = $random;
$your_string = implode(',', $a);
Update - just be careful - if all possible variables will be already in string, it will be endless loop.