1

I tried to use rand() to make it my unique id in database. But how to make sure that this random number will not be duplicated?

<?php

$num = '';
for ($i = 0; $i < 9; $i++)
   $num .= mt_rand(0, 9);
echo '<input name="counter" value="'.$num.'">';
?>
user3097736
  • 284
  • 5
  • 23
  • 2
    `` is not valid PHP code. You should use `print` or `echo`. –  Jan 13 '14 at 15:09
  • 1
    @SharanyaDutta: Of course, it is not. But it clear what the OP is trying to do and the `` element has little to do with the original question that was asked. – Amal Murali Jan 13 '14 at 15:10
  • Then use a conditional statement to first check if it's in the DB first, then in the `else` IF it is found, regenerate another until it is not a duplicate. You can also use the UNIX timestamp, which is another option, in conjunction with `rand()` or `mt_rand()` <= which is faster. – Funk Forty Niner Jan 13 '14 at 15:11
  • 1
    Please start from the beginning, describing what you want to use this number for exactly. This topic is more complex than you may imagine, so knowing what your use case is is essential to recommending you what you should do exactly. – deceze Jan 13 '14 at 15:13
  • 4
    It's probably a better idea to make the field in your database auto-increment rather than trying to pick out random numbers that haven't yet been used. – elitechief21 Jan 13 '14 at 15:14
  • @AmalMurali +1 the question is not about the print or echo. Thanks man ! – user3097736 Jan 13 '14 at 15:23

2 Answers2

-1

In case you want to insert unique values in the database table (that is how I understood you), it is better to create unique index in the database (which ensures that no duplicate entries are in table for the following column. In case of php, check that duplicate value does not already exist in your array.

<?php
  $unique = array();

  while( count($unique) < 9)
  {
    $num = mt_rand(0, 9);

    if( isset($unique[$num]) == false )
       $unique[$num] = true;
  }

  print_r($unique); 
?>
broadband
  • 3,266
  • 6
  • 43
  • 73
  • Or like Amal Murali posted link http://stackoverflow.com/questions/5612656/generating-unique-random-numbers-within-a-range-php use php function range and shuffle. – broadband Jan 13 '14 at 15:27
-2

It's better if you do this way.

First get the range you want with range()

Then you shuffle the array so you can get it in a random order.

Now if you want only 5, you can use array_slice.

$range = range(1, 20);
shuffle($range);
$random = array_slice($range, 0, 5);

print_r($random);

Working example: example

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Jorge Faianca
  • 791
  • 5
  • 11