Trying to code a general 4 digit alphanumeric series in PHP.
Pattern is as follows
0000
0001
....
....
9999
A000
A001
....
....
A999
B000
....
....
Z999
AA00
....
....
AA99
AB00
....
....
ZZ99
AAA0
....
....
AAA9
AAB0
....
....
ZZZZ
I was trying to make the logic based on the no of Z and no of 9, but could not get anything concrete going.
I am trying to write a code that will return me the next number of the series on inputting the last number of the series.
Any hints or leads will be appreciated
This is actually quite easy when using PHP's built-in increment operator which is capable of handling alphanumeric sequences like this.
There are two boundary exceptions that need to be manually handled:
<?php
function getNext($input){
// boundary cases
switch($input){
// bridge numeric to alphanumeric
case '9999': return 'A000';
// terminate sequence, instead of expanding to 5 digits 'AAAA0'
case 'ZZZ9': return 'ZZZA';
// start over
case 'ZZZZ': return '0000';
}
// normal increment
$input = substr(++$input,0,4);
// pad with leading zeros
return str_pad($input, 4, '0', STR_PAD_LEFT);
}
$samples = [
'0000','9999','A000','A999','Z999','AA99',
'ZZ99','AAA9','ZZZ9','ZZZA','ZZZY','ZZZZ'
];
foreach ($samples as $sample)
echo $sample . ' -> ' . getNext($sample) . PHP_EOL;
0000 -> 0001
9999 -> A000
A000 -> A001
A999 -> B000
Z999 -> AA00
AA99 -> AB00
ZZ99 -> AAA0
AAA9 -> AAB0
ZZZ9 -> ZZZA
ZZZA -> ZZZB
ZZZY -> ZZZZ
ZZZZ -> 0000
See this related answer.
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