How to generate a random string with PHP?

Spread the love

Sometimes, we want to generate a random string with PHP.

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

How to generate a random string with PHP?

To generate a random string with PHP, we can cxreate 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 define the generateRandomString that calls rand to get a random number between 0 and $charactersLength - 1 and use the returned value to get a random character from $characters.

We do that in the for loop to create a string with length $length by concatenating the random character to $randomString.

And then we return the string.

Conclusion

To generate a random string with PHP, we can cxreate own function.

Leave a Reply

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