How to generate random string in PHP

In this article, I will show you, how you can generate a random string in PHP. You can set the length of random string. Also, you can define all the possible characters you want in your random string.

In order to generate random string in PHP, we will first create a string of all the possible characters we want in our random string.

$str = "qwertyuiopasdfghjklzxcvbnm";

Then we are going to get the length of that string.

$str_length = strlen($str);

After that, we will create a variable that will hold the output value i.e. random string.

$output = "";

Loop through the number of characters you want in your random string.

$length = 6;

for ($a = 1; $a <= $length; $a++)
{
    // [section-1]
}

On the place of [section-1], we will get the random index from string of possible characters.

$random = rand(0, $str_length - 1);

And we will pick the random character from that string.

$ch = $str[$random];

Finally, we will append that character in our output string.

$output .= $ch;

If you echo $output; you will see a random string every time that code is executed. Here is the full code:

$str = "qwertyuiopasdfghjklzxcvbnm";
$str_length = strlen($str);
$output = "";
$length = 6;
for ($a = 1; $a <= $length; $a++)
{
    $random = rand(0, $str_length - 1);
    $ch = $str[$random];
    $output .= $ch;
}
echo $output;