PHP Function to Generate a Human Readable Word

By | October 4, 2008

Sometimes you need to generate some random strings, that should be readable. A good example is CAPTCHAs: they look much better if there is something like a word on them, not just some random symbols. I’ve created a function (don’t judge me for the code, I know it could be much simpler, but it was created some years ago) that allows to generate a human readable string. Here it is:

function make_username($from, $to)
$arr = array();
for ($i = 97; $i < 123; $i++) {
$arr[] = chr($i);

$glasnye=array(“a”, “e”, “i”, “o”, “u”, “y”);
$soglasnye=array_diff($arr, $glasnye);

// Length
$cout=mt_rand ($from, $to);

$first=mt_rand(0, 1);
if ($first==1)

for ($j=0; $j<=$cout; $j++)
if ($j%2) $usedarray=$array1;
else $usedarray=$array2;
$login.=$usedarray[mt_rand(0, count($usedarray)-1)];
return ($login);

Let me describe, what does this function actually do. First of all, it creates an array of english letters. Then we make 2 separate arrays of consonants and wowels. Then we select a random length (length parameter is selected between two initial values). Then we select which letter will be the first (consonant or wovel), and then try to create a word.

I won’t post any samples here: you’re welcome to try it by yourself. If you can suggest any improvements, I’d greatly appreciate this as I know that the code is not so splendid as it could be.