Im stuck on this for quite some time. I have to work with identifiers that are always 4 characters long and consist of 0-9a-z. An example would be iulz
. So the range would be something like:
0000 0001 0002 ... 0009 000a 000b ... 000z 0010 ... zzzz
So in the case of my example, iulz
I know that the ID before that would be iuly
and after that ium0
. But i cannot seem to work out how to calculate this. The functions hexdec
and dechex
would help me if they would include the whole alphabet.
My first try was to make a logical list with some for loops but this takes an impossible amount of memory. I am looking for a way to make the following two functions:
function getNext(string $id) : string { ... }
function getPrev(string $id) : string { ... }
$this->getNext('iulz') // returns 'ium0'
$this->getPrev('iulz') // returns 'iuly'
Can anyone get me on the right track here? Thnxz!
2
Answers
Your encoding scheme contains 36 symbols (digits from
0
to9
and letters froma
toz
), so a possible approach is to implement a math with Base36. PHP supportsbase_convert()
function to convert a number between arbitrary bases.Result:
As an additional note, you need to define the expected behaviour of the functions, if the
$id
is outside the[0000 .. zzzz]
range.These two functions take an arbitrary alphabet (of unique characters). The id can be of any length smaller than the length of the alphabet string. Both error condition could and should be added to these function.
If there is no preceding value for previousId the function currently returns a message for illustration purposes. Possible real values: false, null, wrap around to the last value (‘zzzz’), or maybe throw a
RuntimeException
or test the input value before calling previousId. Same applies for a call of nextId with an id of ‘zzzz’, which could return ‘0000’, or false, or null, etc.