Jeffrey L. Roberts Jeffrey L. Roberts - 7 months ago 11
PHP Question

Increment alphanumerically with numbers after z in PHP

I am looking to increment strings in php where after z the next increment is numeric.

a..aa..ab..az..a0

I have tried the following and several other attempts, any ideas or suggestions are greatly appreciated.

<?php

$start = 'a';
$end = '999';
while($start != $end)
{
$start = ++$start;
echo $start . "\n";
}


however the results look like this

a
b
...
aaaa


If I add a number to the end of $start like as follows

<?php

$start = 'a1';
$end = '999';
while($start != $end)
{
$start = ++$start;
echo $start . "\n";
}


The results look like this

a1
a2
...
aa1
...
az9
ba0


The results I am looking for should look like

a1
a2
...
aa1
...
az9
a00
a01
...
ba0

Answer

Well, the ++ is pretty strictly defined in what it does - increments characters by ASCII values, for a very limited range of characters, so your problem will most likely need a custom solution.

I tried:

$start = 'a';
$end = '999';
$seq = 'abcdefghijklmnopqrstuvwxyz0123456789';

while($start != $end)
{
    echo $start . "\n";

    $pass = 1;
    for ($i = strlen($start) - 1; $i >= 0; $i--) {
        if (!$pass) break;
        else $pass--;

        $last = substr($start, $i, 1);
        $pos = strpos($seq, $last);

        if ($pos == strlen($seq) - 1) {
            $pos = 0;
            $pass++;
        } else $pos++;
        $start[$i] = $seq[$pos]; 
    }
    if ($pass) $start .= substr($seq, 0, 1);
}

which, if you accept my comment, gets you the sequence you seem to want. All the code does is manually go through $start backwards, incrementing the character to the next one in $seq and, if it's the last one, set it to the first one and "carry the one". Really, it's just a character sum.