Incrementing / Decrementing a String with PHP

In the past, we’ve discussed incrementing and decrementing a variable and incrementing and decrementing a number by another number but did you know that we can also increment and decrement a string? You can use the shorthand operators ++ or -- to accomplish this. Please note that you can’t increment or decrement a string by another number, only with the shorthand operators.

$string = 'a'

while ($string != 'zzz')
{
	echo ++$string . "n"
}

The above infinite loop will loop through incrementing the string which starts at lowercase a all the up to zzz. PHP follows the Perl convention for incrementing and decrementing strings, not the C convention would increment according to the ASCII values and not just alphanumerics.

Speaking of numerics, you can also increment and decrement a string that contains numbers which will increment both the alphabetic portion as well as the numeric portion:

$string = 'AA0'

while ($string != 'ZZZ9')
{
	echo ++$string . "n"
}

Pretty cool stuff, but to be honest, I’ve never once used this before for anything I’ve ever built. I could see it perhaps being used to suggest a username when someone requests a username that’s already in the system. “Sorry john123 is already taken, would you like to use john124?” or something like that. If you’ve had to increment or decrement a string for something aside from a homework assignment, I’d love to hear about it, comment below!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.