Vidya L
Vidya L

Reputation: 2314

Generate random number without duplicates

I want to generate 6 digit random number and check whether it is in table, if it exists generate another 6 digit random number and check again and so on .. the code wriiten is following,

$querySel1=mysqli_query($connect, "select dynamic_email_id from logis_contacts");
while($row = mysqli_fetch_row($querySel1)){
  $dynamic_id[] = $row[0];              
}
$number = mt_rand( 100000, 999999);
dynamicEmailId($number, $dynamic_id);


function dynamicEmailId($number, $dynamic_id){
  if( in_array($number, $dynamic_id) ){     
     $new  = mt_rand( 100000, 999999);
     dynamicEmailId($new, $dynamic_id);// here i am confused
   }
  else {
    echo $number;
  }
}

please suggest a better way to achieve this

Upvotes: 2

Views: 1334

Answers (1)

Sibiraj PR
Sibiraj PR

Reputation: 1481

*It's fine please check

function generateUniqueId($number,$fetchArray) {
  if (!in_array($number,$fetchArray)) { 
    return $number;
  }
  else {
    $newNumber  = mt_rand( 100000, 999999);
    return generateUniqueId($newNumber, $fetchArray);
  }
 }

Upvotes: 1

Related Questions