Search code examples
phpstrpos

php random number find in string


I'm randomly picking a number from a function that's assigned string $randomID. Then I build a string $checkIDas = '|'.$randomID.'|'; Then if the random number has been used before then forget it and try again. The problem is I don't get errors and the page just hangs. I know my random number function works, and my query works. But when I add the if strpos statement, that's when it hangs. Any suggestions?

function randomNumber($min, $max) {
  $rand = base_convert( md5( microtime() ), 16, 10);
  $rand = substr($rand, 10, 6);
  $diff = $max - $min + 1;
  return ($rand % $diff) + $min;
}

$sp = 1;
$usedUsers = "|0|";
while($sp < 7) {
    $randomID = randomNumber(1,55);
    $checkIDas = "|".$randomID."|";
    if (strpos($usedUsers,$checkIDas) !== false) {
        //Run my Query
        $sp ++;
        $usedUsers = $usedUsers . $randomID."|";
    }
}

Solution

  • The problems have been already pointed out by others, I'd like to add that you could make your life easier by using appropriate language constructs, like putting used ids in an array and look them up there:

     ...
     $usedUsers = Array();  // this will hold the id list
     ...
    
     ...
     $sp = 1;
     while($sp < 7) {
         // get $randomID from somewhere 
         if( ! in_array($randomID, $usedUsers) ) {
             // Run my Query
             $sp++;                      // increment counter
             $usedUsers[] = $randomID;   // add new id to array
         }
     }
     ...
    

    (Pseudocode, modify according to your requirements.)

    Regards

    rbo