Search code examples
phpstringnumbersdigit

How can I make a "number" with string in PHP?


Instead of using the [0..9] symbols use the [0..9A..Z] symbols

Instead of using the base-10 system use the base-64 system

I want to make a function like in this example:

next('ABC') return 'ACA' - this is the next string with 3 units

It is like we have numbers from 0 to 9 and the function return the next number

next2(135) return 136 - this is the next number with 3 digits

We use a base-10 system for numbers an I want to use numbersletters that means a base-36 system, and get the next so called number


Solution

  • Here's a function that produces the next value in your base-3 alphabetic number system:

    function nextval($input, $pad = 1) {
    
            $map = array(0 => 'A', 1 => 'B', 2 => 'C');
    
            //convert letters to numbers
            $num = '';
            for ($i = 0; $i < strlen($input); $i++) {
                    $num .= array_search($input{$i}, $map);
            }
    
            //convert the number to base 10, then add 1 to it
            $base10 = base_convert($num, 3, 10);
            $base10++;
    
            //convert back to base 3
            $base3 = base_convert($base10, 10, 3);
    
            //swap the digits back to letters
            $num = '';
            for ($i = 0; $i < strlen($base3); $i++) {
                    $num .= $map[$base3{$i}];
            }
    
            //pad with leading A's
            while (strlen($num) < $pad) {
                    $num = 'A' . $num;
            }
    
            return $num;
    
    }
    
    echo nextval('ABC', 3); //ACA
    

    Note that the result is "CA" as "ACA" is the same as writing "06" in base-10... we don't usually write leading zeros so you wouldn't write leading "A"s.

    I therefore added a pad parameter that lets you specify what number of digits you want to pad to. With $pad=3, you get "ACA" as next from "ABC".