How to create a PHP random string generator?

Spread the love

Sometimes, we want to create a PHP random string generator.

In this article, we’ll look at how to create a PHP random string generator.

How to create a PHP random string generator?

To create a PHP random string generator, we can create our own function.

For instance, we write

function generateRandomString($length = 10)
{
    $characters =
        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $charactersLength = strlen($characters);
    $randomString = "";
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

to create the generateRandomString function that takes the $length of the string to generate.

In it, we have a for loop that loops from 0 to $length - 1.

In the loop, we get a random character from $characters with

$randomString .= $characters[rand(0, $charactersLength - 1)];

Then we return the $randomString.

Conclusion

To create a PHP random string generator, we can create our own function.

Leave a Reply

Your email address will not be published. Required fields are marked *