I need to generate a sequence (or function to get a \"next id\") with an alphanumeric incrementor.
The length of the string must be defineable, and the Characters mu
I was interested in the more general solution to this problem - i.e. dealing with arbitrary character sets in arbitrary orders. I found it easiest to first translate to alphabet indexes and back again.
function getNextAlphaNumeric($code, $alphabet) {
// convert to indexes
$n = strlen($code);
$trans = array();
for ($i = 0; $i < $n; $i++) {
$trans[$i] = array_search($code[$i], $alphabet);
}
// add 1 to rightmost pos
$trans[$n - 1]++;
// carry from right to left
$alphasize = count($alphabet);
for ($i = $n - 1; $i >= 0; $i--) {
if ($trans[$i] >= $alphasize) {
$trans[$i] = 0;
if ($i > 0) {
$trans[$i -1]++;
} else {
// overflow
}
}
}
// convert back
$out = str_repeat(' ', $n);
for ($i = 0; $i < $n; $i++) {
$out[$i] = $alphabet[$trans[$i]];
}
return $out;
}
$alphabet = array();
for ($i = ord('0'); $i <= ord('9'); $i++) {
$alphabet[] = chr($i);
}
for ($i = ord('A'); $i <= ord('Z'); $i++) {
$alphabet[] = chr($i);
}
echo getNextAlphaNumeric('009', $alphabet) . "\n";
echo getNextAlphaNumeric('00Z', $alphabet) . "\n";
echo getNextAlphaNumeric('0ZZ', $alphabet) . "\n";