Generate sequential strings for URL addresses using PHP
Aditya January 23rd
I’m working on an interesting project right now, and for this project, I wanted to generate URLs with sequential alphabetic sequence as opposed to using numeric IDs. Using alphabetic string allows me to use short URL addresses with many URL combinations. E.g. If I use numeric indexes, then I can only have 10 possibilities to represent http://abc.com/N, where N= 0 to 9. But instead, if I use alphabetic character, I have 26 possibilities where N= a, b, c to z. I don’t want to add usability issues by using both upper and lower cases of alphabets, so I’ll stick to lower case addresses only.
So I needed a function which will generate sequential alphabetic strings for URL address based on incremental numbers. So I coded up following function:
function getAlphaString($num)
{
$alpha = '';
while($num >= 1) {
$num = $num - 1;
$alpha = chr(($num % 26)+97) . $alpha;
$num = $num / 26;
}
return $alpha;
}
Use this in a for{} loop, and it will give you sequential strings. Or call with individual numbers as shown below, and it will return you appropriate alphabetic string.
echo getAlphaString(5) . "\n"; echo getAlphaString(500) . "\n"; echo getAlphaString(500000) . "\n"; echo getAlphaString(50000000) . "\n";
And it produced following output:
e sf abkpt dejtlx
Hope you’ll find this function useful in one of your applications.