Skip to content

How to generate random string PHP

Generating random strings can be very useful in lot of cases.It might be for a verification code or a password etc.

Below is the simple function by using this function you can generate random string. Basically this function takes/accepts one parameter called $length. Based on this value random string will be generated in the given length.

function random_string($length)
{
    // we are using only this characters/numbers in the string generation  
    $chars ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
    $string =''; // define variable with empty value
    // we generate a random integer first, then we are getting corresponding character , then append the character to $string variable. we are repeating this cycle until it reaches the given length 
    for($i=0;$i<$length; $i++) 
    {
        $string .= $chars[rand(0,strlen($chars)-1)];
 
    }
    return $string ; // return the final string 
}

Instead of looping we can use below snippet. But if you require a random String that has a greater length than $chars itself, this alternative method will not work.

  // str_shuffle -  randomly move characters around in the String
  // substr -  return part of a string
  $str = substr( str_shuffle( $chars ), 0, $length );

That's it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments