Join the community and participate in the ongoing discussions. Join Now!
How to Generate a random string in PHP
If you need to generate a random string using php, you can use this function below;
function randomString($length) {
     $returnStr = "";
     $characters = array_merge(range('A','Z'), range('a','z'), range('0','9'));
     $max = count($characters) - 1;
   for ($i = 0; $i < $length; $i++) {
          $randChar = mt_rand(0, $max);
          $returnStr .= $characters[$randChar];
return $returnStr;

array_merge, mt_rand, count and range are all built-in PHP methods.
The array_merge() is resposible for merging two or more arrays. It's function is to merge three different arrays created by the range() methods.
The range() method creates an array of a range of characters depending on what is defined for it. It takes three(3) parameters/arguments. The first is the start value/character of the sequence, the second is the last value/character of the sequence, while the third which optional is the step which will be used as the increment between elements in the sequence.
NOTE: There is no third argument in the example above since it is optional.
The count() method is just to count the number of character generated.
Lastly, mt_rand() is a method that generate a random value. It takes two(2) parameters/arguments. The first is the min value while the second is the max value.

$returnStr was initialized to be an empty string, $character was assigned, an array of characters ranging from 0-9, a-z and A-Z.
$max was assigned the last array index by reducing the array lenght by one (-1) considering the fact that an array starts from zero(0).
$lenght is determined by the agument passed into the function which will also determine how many character (string lenght) will be generated by the function.
Using the for loop, the $randChar holds a character generated from the mt_rand() method which is then accumulated in the $returnString variable. The variable is finally returned by the function as the callback/result.

You can place the in your page or an external page included or required by the main page where you want to use it. Then assign the function into a variable placing the desired number of string into it as the argument.

For Instance, if I need an eight(8) string random values I will use the function as bellow;
$myRandomStr = randomString(8)

and that's it. Destiny Brotobor
27th Dec, 2018 @ 08:45 pm