Incrementing / Decrementing a String with PHP

Josh Sherman
1 min read
Software Development 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!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

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

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles