Reputation: 6247
I am working on something where I need to generate the sequence 1,2,3...a,b,c,d...z,11,12,13...aa,ab,ac...zzzzzzzz, using php. This will only ever have to happen once, so it dosen't need to be very fast.
Thanks!
Upvotes: 1
Views: 546
Reputation: 1034
I recently had to do this with a non-standard set of character (they left out certain characters).
I put together a few functions I found on the net and got:
// this array misses a few letters due to the special naming convention
private $alphabet = array('0', '1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z');
private function createDecimalFromCode($string){
$decimal = 0;
$base = count($this->alphabet);
$charset = implode($this->alphabet, '');
$charset = substr($charset, 0, $base);
do {
$char = substr($string, 0, 1);
$string = substr($string, 1);
$pos = strpos($charset, $char);
if ($pos === false) {
$error[] = "Illegal character ($char) in INPUT string";
return false;
} // if
$decimal = ($decimal * $base) + $pos;
} while($string <> null);
return $decimal;
}
private function createCodeFromDecimal($decimal){
$s = '';
while($decimal > 0) {
$s = $this->alphabet[$decimal%sizeof($this->alphabet)] . $s;
$decimal = floor($decimal/sizeof($this->alphabet));
}
return $s == '' ? '0' : $s;
}
Essentially I take my last created code, convert it to a decimal, add 1 and then convert that back to the next alphanumeric code.
Upvotes: 0
Reputation: 10091
function incrementAlphanumeric($number) {
return base_convert(base_convert($number, 36, 10) + 1, 10, 36);
}
echo incrementAlphanumeric(9); // outputs "a"
To populate an array:
$number = 1;
$numbers = array();
while ($number != 'zzzzzzzz') {
$numbers[] = $number;
$number = incrementAlphanumeric($number);
}
Upvotes: 2