Archive for the ‘Programming’ Category

Random string help with PHP’s range function

Tuesday, July 24th, 2007

When I began developing in PHP, I remember needing a complete random string, for passwords/verification emails. The code for it went a little something like this:

$letters = array('A', 'B', 'C', ... etc);

Being a novice programmer, I used to ask people for help and let them see my code. Anyhow, to make a long story short, I met Peter Harkins on Freenode’s #php channel. He showed me the range() function, which helped shorten my code, and make it look cleaner. Below is a simple function that can be used, may be useful to some, that can shorten the process.

<?php
function range2($start, $end, $length)
{
$str_array = range($start, $end);
srand((double) microtime() * 1000000);
$text = '';
for($i = 0; $i < $length; $i++)
{
$text .= $str_array[rand(0, count($str_array) - 1)];
}
return $text;
}
?>

Example:
<?php
echo range2('A', 'Z', 5);
?>

How it works:
Creates an array of letters from ‘A’ to ‘Z’ using ascii characters. Check out www.asciitable.com for the ordering of them. Afterwards, it selects a random letter from the array and assigns it to the $text variable.

Not too hard, just something I feel is simple and useful. Since I tend to see alot of developers still doing it the “hard” way.