3

How to get a fixed length string without using the rand() function?

I have this but I do not want to use the rand() function

function generateRandomString($length =6) {
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';

    for ($j = 0; $j < $length; $j++) {
        $randomString .= $characters[mt_rand(0, $charactersLength - 1)];
    }

  return $randomString;
 }
Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
Rafiqul Islam
  • 1,636
  • 1
  • 12
  • 25

3 Answers3

2
<?php
$start=0;$length=6;
$str='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$Val=substr(str_shuffle($str),$start,$length);
echo $Val;
?>  
1
function mt_rand_str ($l, $c = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') {

     for ($s = '', $cl = strlen($c)-1, $i = 0; $i < $l; $s .= $c[mt_rand(0, $cl)], ++$i);
        return $s;
}


Here you can call this function for 8 character

mt_rand_str(8)
Lemon Kazi
  • 3,308
  • 2
  • 37
  • 67
Nilesh Daldra
  • 69
  • 1
  • 9
0

you can use following code to get fixed length random string

<?php
$str = 'abcdef';
$shuffled = str_shuffle($str);

 // this will genrate randome string with fixed string lenght
echo $shuffled;
?>
ram singh
  • 117
  • 5