Generating Random String Using PHP

Generating Random String Using PHP

Generating random strings with custom specified length is most required functionality in every project. In this article, I described the easiest way to generate custom length random string.

PHP program for Random String Generate:

<?php
 /*
 * Function to generate random string
 * Default length 30 character
 */
 function generateRandomString($length = 30)
 {
 // Control random character by manual
 $wordArray = explode(",", "a, b, c, d, e, f, g, h, i, j, k, l, m, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0"); 

 //Shuffle array values
 shuffle($wordArray); 

 //Merge shuffled array values into string and fetch first X ($length) characters
 return substr(implode($wordArray, ""), 0, $length);
 }
 echo "Random string with length 30: ".generateRandomString();
 echo "Random string with length 10: ".generateRandomString(10);
 echo "Random string with length 8: ".generateRandomString(8);
 ?>

Creating an array with the name ‘$wordArray‘. Store custom required random string characters.

// Control random character by manual
$wordArray = explode(",", "a, b, c, d, e, f, g, h, i, j, k, l, m, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0");

Now, shuffle the random string character array with the default PHP function ‘shuffle()‘. It randomizes the order of the elements in an array.

//Shuffle array values
shuffle($wordArray);

After shuffled, merge the given array value into a string by using default PHP function ‘implode‘ and split / fetch $length character from the first position.

//Merge shuffled array values into string and fetch first X ($length) characters
return substr(implode($wordArray, ""), 0, $length);

Note: You can also split the string with custom position.

//Merge shuffled array values into string and fetch first X ($length) characters
return substr(implode($wordArray, ""), 5, $length); # It will fetch from 5 th position

Output:

Random string with length 30: m1ehb9f36d0j2k854ai7gcl
Random string with length 10: 04gjbhlm9a
Random string with length 8: 8b49ah0f

You Might Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *