views:

184

answers:

3

I want to generate a random number in PHP where the digits itself should not repeat in that number. Is that possible? Can you paste sample code here? Ex: 674930, 145289. [i.e Same digit shouldn't come] Thanks

+6  A: 

Here is a good way of doing it:

$amountOfDigits = 6;
$numbers = range(0,9);
shuffle($numbers);

for($i = 0;$i < $amountOfDigits;$i++)
   $digits .= $numbers[$i];

echo $digits; //prints 217356

If you wanted it in a neat function you could create something like this:

function randomDigits($length){
    $numbers = range(0,9);
    shuffle($numbers);
    for($i = 0;$i < $length;$i++)
       $digits .= $numbers[$i];
    return $digits;
}
Sam152
i would even do it like that: echo intval(implode('', array_splice($numbers, $amountOfDigits)));
kgb
That's an okay solution, but is a little hard to read and uses string functions.
Sam152
A: 
function randomize($len = false)
{
   $ints = array();
   $len = $len ? $len : rand(2,9);
   if($len > 9)
   {
      trigger_error('Maximum length should not exceed 9');
      return 0;
   }
   while(true)
   {
      $current = rand(0,9);
      if(!in_array($current,$ints))
      {
         $ints[] = $current;
      }
      if(count($ints) == $len)
      {
          return implode($ints);
      }
   }
}
echo randomize(); //Numbers that are all unique with a random length.
echo randomize(7); //Numbers that are all unique with a length of 7

Something along those lines should do it

RobertPitt
Thanks Sam. This was the code I was looking..
sanjeevkanna
Robert, Thank you very much for the code..
sanjeevkanna
Your welcome, Remember to select the answer that you think was best na click the tick next to it.
RobertPitt
A: 
$result= "";
$numbers= "0123456789";
$length = 8;

$i = 0; 

while ($i < $length) 
{ 
    $char = substr($numbers, mt_rand(0, strlen($numbers)-1), 1);
    //prevents duplicates
    if (!strstr($result, $char)) 
    { 
        $result .= $char;
        $i++;
    }
}

This should do the trick. In $numbers you can put any char you want, for example: I have used this to generate random passwords, productcodes etc.

Jurgen