Home » PHP8 September 2011

PHP: Generating Multiple Random String

Here is a quick way to generate random strings in PHP. I will be showing how you can generate multiple random strings at once. You can specify the number of letters in the random string generated. You can also specify the total number of words you want to generate.

I have used str_shuffle function to shuffle the string and then substr function is used to fetch a portion of the string.

Here is the code:-

”;

Hope this helps. Thanks.

PHP

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed
  • Ct

    Just a variation, should be faster than combining str_shuffle and substring. 
    // string from which random strings are generated
    $string = ‘abcdefghijklmnopqrstuvwxyz’;

    $len = strlen($string)-1; 
    // result array of random strings
    $result = array();
     
    // number of letters in the random string to be generated
    $letters = 3;
     
    // total number of word you want to generate
    $num = 10;
    for ($i=0;$i<$num;$i++) {
    $word = "";
    for($j=0;$j<$letters;$j++)
    $word .=  $string[rand(0,$len)];
    $result[] = $word;
    }

    echo "”; print_r($result); echo “”;