Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alphanumeric Increment a string in PHP (To a certain length)

Tags:

php

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?

like image 722
Dean Rather Avatar asked Sep 03 '25 05:09

Dean Rather


2 Answers

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 ...

like image 159
jlmcdonald Avatar answered Sep 04 '25 19:09

jlmcdonald


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;
}
like image 44
Phil Avatar answered Sep 04 '25 21:09

Phil