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 must be 0-9, A-Z.
So for example, with a length of 3:
000
001
002
~
009
00A
00B
~
00Z
010
011
etc..
So I imagine the function might be used like this:
$code = '009'
$code = getNextAlphaNumeric($code);
ehco $code; // '00A'
I'm working on a solution to this myself, but curious if anyone has tackled this before and come up with a smarter / more robust solution than my own.
Does anyone have a nice solution to this problem?
Would something like base_convert work? Maybe along these lines (untested)
function getNextAlphaNumeric($code) {
$base_ten = base_convert($code,36,10);
return base_convert($base_ten+1,10,36);
}
The idea is that your codes are all really just a base 36 number, so you convert that base 36 number to base 10, add 1 to it, then convert it back to base 36 and return it.
EDIT: Just realized that there may be an arbitrary string length of the code, but this approach might still be doable -- if you capture all the leading zeroes first, then strip them off, do the base 36 -> base 10 conversion, add one, and add back any needed leading zeroes ...
I would do something like this:
getNextChar($character) {
if ($character == '9') {
return 'A';
}
else if ($character == 'Z') {
return '0';
}
else {
return chr( ord($character) + 1);
}
}
getNextCode($code) {
// reverse, make into array
$codeRevArr = str_split(strrev($code));
foreach($codeRevArr as &$character) {
$character = getNextChar($character);
// keep going down the line if we're moving from 'Z' to '0'
if ($character != '0') {
break;
}
}
// array to string, then reverse again
$newCode = strrev(implode('', $codeRevArr));
return $newCode;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With