PHP: Incrementing/decrementing a numeric string that has letter (alpha) prefixes

I see this question quite a bit in programming discussions and forums. I’ll be linking to this post from now on to avoid re-posting the same replies every time someone asks.

String Value: XYZ123

Desired Result: XYZ124

The majority of solutions I have read regarding this problem require splitting the string or using regular expressions to manipulate the numeric portion. The overhead for complex solutions for such a simple problem are simply overkill. The example below shows the easiest way to increment the string  and requires minimal overhead…

$str = 'XYZ123';
echo $str++; // Output: XYZ124

It couldn’t be any easier. To decrement, simply modify the ‘++’ operator as follows…

$str = 'XYZ123';
echo $str--; // Output: XYZ122

Now, if your numeric string ends with a letter, this method will perform differently than you might expect.

$str = '123ABC';
echo $str++; // Output: 123ABD

Here as an example performed using a for loop.

<?php
$str = '35A990';
for ($i = 0; $i < 16; $i++) {
    echo $str++ . ' ';
}
// Output: 35A990 35A991 35A992 35A993 35A994 35A995 35A996 35A997 35A998 35A999 35B000 35B001 35B002 35B003 35B004 35B005
?>

Note: Since we exceeded the upper limit of the numeric portion, the preceding alpha character ‘A’ is incremented to ‘B’ (in red above). Be sure you understand this behavior before implementing this method.

Feel free to comment if you have any questions.

Leave a Reply

Your email address will not be published.