PHP – Generate a Random String with A-Z and 0-9

This example shows you how to generate a random string with A-Z and 0-9 using the str_shuffle built-in PHP function, which lets us shuffle a string randomly.

StringExample.php
function generateRandomString($length = 20) {
    $randomString = str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
    return substr($randomString, 0, $length);
}

Use the function:

echo generateRandomString(); // QyxEVhdFZkGI7pB1UCRi
echo generateRandomString(10); // eSVzyOTvCu
echo generateRandomString(30); // hoNwLAV35Ux8EISYd7qZ6OmjiJsGuD

0 0 vote
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x