PHP Random Number

2019-04-11 01:51发布

问题:

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

回答1:

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;
}


回答2:

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



回答3:

<?php
function genRandomString() {
$length = 10;  // set length of string
$characters = '0123456789';  // for undefined string
$string ="";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}

 $s = genRandomString(); //this is your random print var 


or


function rand_string( $length )
{
$chars = "0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ )
{
$str .= $chars[ rand( 0, $size – 1 ) ];
}
return $str;
}
$rid= rand_string( 6 ); // 6 means length of generate string


?>


回答4:

$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.



回答5:

The least amount of code I saw for something like this was:

function random_num($n=5)
{
    return rand(0, pow(10, $n));
}

But I'm assuming it requires more processing to do this than these other methods.