- Instant help with your Php coding problems

Generate random string with PHP

Generating random strings can be very useful in a lot of cases. You can generate random passwords, validation codes, and so on. The main points in random string generation are the followings:

  • Define the valid characters that can be used in the string
  • Define the length of the string
  • Generating a random number

So after you have a list of the usable characters then you need to select one of them randomly and add it to a result string. Repeat it until the length of the result string is sufficient.

To define the valid characters simple use a string and initialize it with the allowed characters like this:

$validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ+-*#&@!?";

The length of the requested string can be an input parameter of the function.

To get a random character from our list we need to use a random number generator function. In PHP there are more possibilities. The original rand() function is slow and its algorithm is not as good as the newer mt_rand() so we use mt_rand(). As parameters, we can define a minimum and a maximum value so the generated number will be between these values. For example, if you want to generate random numbers between 0 and 10 then you can do it like this:

$index = mt_rand(0, 10);
 
echo $index;

In our case, the minimum value is 0 and the maximum value is the length of the valid string variable minus one. This is because we handle the string as an array and the first index of the array is 0. Accordingly selecting one random character from the valid character list is the following:

$validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ+-*#&@!?";
$validCharNumber = strlen($validCharacters);
 
$index = mt_rand(0, $validCharNumber-1);
$randomCharacter = $validCharacters[$index];
 
echo $randomCharacter;

What we need next is to surround this code with a loop to generate the string with the requested length:

$length = 5;
$result = "";
 
for ($i = 0; $i < $length; $i++) {
    $index = mt_rand(0, $validCharNumber-1);
    $result .= $validCharacters[$index];
}

Finally, we can put it all together in a simple function as here:

function getRandomString($length = 6) {
    $validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ+-*#&@!?";
    $validCharNumber = strlen($validCharacters);
 
    $result = "";
 
    for ($i = 0; $i < $length; $i++) {
        $index = mt_rand(0, $validCharNumber - 1);
        $result .= $validCharacters[$index];
    }
 
    return $result;
}
 
echo getRandomString();

Share "Generate random string with PHP" with your friends