PHP: Get a random character from a string.

This is a short tutorial on how to get a random character from a string using PHP. To do this, we will use PHP’s mt_rand function.

Let’s take a look at the following example:

//Our string.
$string = 'ABCDEFG';

//Get the length of the string.
$stringLength = strlen($string);

//Generate a random index based on the string in question.
$randomIndex = mt_rand(0, $stringLength - 1);

//Print out the random character.
echo $string[$randomIndex];

In the PHP above:

  1. We created a string. In this case, it’s just the first seven letters of the alphabet.
  2. We determined the length of the string by using the strlen function.
  3. After that, we used PHP’s mt_rand function to generate a random index based on the length of the string. In PHP, you can access specific characters in a string like you would access array elements.  For instance, the letter “A” in $string could be accessed using $string[0].
  4. Finally, we used that randomly-generated index to print out a character from our string.

For the purposes of this tutorial, the example above is pretty long-winded and verbose. However, we can shorten it like so:

//Our string.
$string = 'ABCDEFG';

//Print out the random character.
echo $string[mt_rand(0, strlen($string) - 1)];

Get 5 random characters from a string.

What if we want to retrieve five or six random characters from a string? For this scenario, we can use a custom-built function:

/**
 * Function that retrieves a set number of random characters
 * from a string.
 *
 * @param $str The string that you want to get random characters from.
 * @param $numChars The number of random characters that you want.
 */
function randomChars($str, $numChars){
    //Return the characters.
    return substr(str_shuffle($str), 0, $numChars);
}

The function above takes in two parameters:

  1. The string that you want to retrieve characters from.
  2. The number of characters that you want.

A few examples of this function being used:

//Our string.
$string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

//Getting 4 random characters.
echo randomChars($string, 4), '<br>';

//Getting 5 random characters.
echo randomChars($string, 5), '<br>';

//Generate 6 random characters.
echo randomChars($string, 6), '<br>';

As you can see, it’s pretty simple!

Warning!

It is important to note that this method is not cryptographically secure. i.e. You should not be using this method to generate random passwords or password salts. This is because the output of functions such as rand and mt_rand can be predicted.

If you are looking to generate a random string that is cryptographically secure, then you should check out this guide. You can also take a look at my posts on random numbers and secure passwords.