How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?
Method 1: Using Math. random() Here the function getAlphaNumericString(n) generates a random number of length a string. This number is an index of a Character and this Character is appended in temporary local variable sb. In the end sb is returned.
Example 1: Using the rand() Function to Generate Random Alphabets in C++ The following C++ program generates a random string alphabet by using rand() function and srand() function. The rand() function generates the random alphabets in a string and srand() function is used to seed the rand() function.
Initialize an empty string and name it as “randomString”. Choose the size of the string to be generated. Now using Next() method generate a random number and select the character at that index in the alphanumeric string. Append that character to randomString.
First make a string with all your possible characters:
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
You could also use range() to do this more quickly.
Then, in a loop, choose a random number and use it as the index to the $characters
string to get a random character, and append it to your string:
$string = ''; $max = strlen($characters) - 1; for ($i = 0; $i < $random_string_length; $i++) { $string .= $characters[mt_rand(0, $max)]; }
$random_string_length
is the length of the random string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With