Generating Random String in PHP


Read {count} times since 2020

In PHP you can generate random number by using rand function, but there is no specific function to generate a random text or string. In this post I’m going to show the function that will generate a random string of length mentioned.

Here is the function:

function rand_string($length) {
 $chars = "subinsblogabcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
 $size = strlen($chars);
 for($i = 0;$i < $length;$i++) {
  $str .= $chars[rand(0,$size-1)];
 return $str;


To generate a random string use rand_string() function with the parameter of length of the to be generated string. Here’s an example:

echo rand_string(6);

The above code will print out something like this :


Note that the above printed out string will be different for everyone, not the same.


  1. The first variable $str is the variable where the function adds random single strings to make the long random string.
  2. The variable $chars contains lots of characters including integers and alphabetic letters. You can change it if you want.
  3. The $size variable contains the number of characters in the $chars string.
  4. Now it’s looped at n times where n is the length of to be generated string we mentioned in the function.
  5. At each loop a character is added to the $str variable from random letter got from the $chars variable.
  6. And finally the generated string is returned.
Show Comments