Link to home
Start Free TrialLog in
Avatar of krutarth941
krutarth941

asked on

Code for generating a random string

Hello, can you please explain me the following code for generating a random string.

function generateRandStr($length){
$randstr = "";
for($i=0; $i<$length; $i++){
$randnum = mt_rand(0,61);
if($randnum < 10){
$randstr .= chr($randnum+48);
}else if($randnum < 36){
$randstr .= chr($randnum+55);
}else{
$randstr .= chr($randnum+61);
}
}
return $randstr;
Avatar of Brad Brett
Brad Brett
Flag of United States of America image

It generate random numbers and convert them to chars using chr() method.

chr() returns a one-character string containing the character specified by ascii:
http://php.net/manual/en/function.chr.php
ASKER CERTIFIED SOLUTION
Avatar of Frozenice
Frozenice
Flag of Philippines image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of krutarth941
krutarth941

ASKER

Thank you for the information.

I don't understand why it adds 48, then 55 and then 61.
I don't understand this portion. Could you please explain me in brief.
$randnum = mt_rand(0,61);
if($randnum < 10){
$randstr .= chr($randnum+48);
}else if($randnum < 36){
$randstr .= chr($randnum+55);
}else{
$randstr .= chr($randnum+61);
}
}
return $randstr;
Thank you very much Frozenice. I got it.
Excellent answer
Hi

function generateRandStr($length) //Function declaration which is overriding method with Parameter.
{  
$randstr = "";   //Defining string null.
//Loop through value of parameter passed
for($i=0; $i<$length; $i++)  {  
/* mt_rand is PHP Function to generate random value. Calling that function will return random value with between 0 - 61 where 0 is min & 61 is max. More info :http://php.net/manual/en/function.mt-rand.php*/
$randnum = mt_rand(0,61);   // store mt_rand return value to $randnum
 
/*if condition to check for value fetch is less than with given value.
chr() will returns a one-character string containing the character specified by ascii.  More info http://php.net/manual/en/function.chr.php   

You can also get ascii value details here http://www.asciitable.com/
*/

if($randnum < 10){  
$randstr .= chr($randnum+48);
}else if($randnum < 36){
$randstr .= chr($randnum+55);
}else{
$randstr .= chr($randnum+61);
}
}
return $randstr;
}  // I have added closing curly braces. I think you forgot to put.

Thanks.
no problem, im glad id of any help.



br
Thank you sumi for your help. Thanks a lot.