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:

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:

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:

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:

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 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.

Facebook Comments