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) {
$str="";
$chars = "subinsblogabcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0;$i < $length;$i++) {
$str .= $chars[rand(0,$size-1)];
}
return $str;
}
Usage
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 :
oSuN1R
Note that the above printed out string will be different for everyone, not the same.
Explanation
- The first variable $str is the variable where the function adds random single strings to make the long random string.
- The variable $chars contains lots of characters including integers and alphabetic letters. You can change it if you want.
- The $size variable contains the number of characters in the $chars string.
- Now it’s looped at n times where n is the length of to be generated string we mentioned in the function.
- At each loop a character is added to the $str variable from random letter got from the $chars variable.
- And finally the generated string is returned.