One-Line Random String Generators


The following code generates a string of 32 random characters (letters and numbers):

echo implode("",array_map(create_function('$s','return substr($s,mt_rand(0,strlen($s)),1);'),array_fill(0,32,"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")));

Here it is again, formatted for readability:

echo implode("", array_map(
    create_function('$s', 'return substr($s, mt_rand(0, strlen($s)), 1);'),
    array_fill(0, 32, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

If you need a different length, change the 32 to another value, obviously. If you want to select from different characters, change the character string.

Note: The performance of this code is not great. If you need something fast, you might want to look at other options.