PHP random number

I want to create a random number in PHP where numbers should not be repeated in that number. Is it possible? Can you insert sample code here? Example: 674930, 145289. [The same number should not arrive] Thank you

+3
source share
5 answers

Here is a good way to do this:

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

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

echo $digits; //prints 217356

If you want a neat function, you can create something like this:

function randomDigits($length){
    $numbers = range(0,9);
    shuffle($numbers);
    for($i = 0;$i < $length;$i++)
       $digits .= $numbers[$i];
    return $digits;
}
+13
source
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 these lines should do it

+3
source
<?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


?>
+1
$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++;
    }
}

. $numbers char, , : , ..

0

, - , :

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

But I assume that this requires more processing than these other methods.

0
source

Source: https://habr.com/ru/post/1752265/


All Articles