Most efficient way to get next letter in the alphabet using PHP

Mathias Bynens picture Mathias Bynens · Apr 20, 2010 · Viewed 44k times · Source

Given any character from a to z, what is the most efficient way to get the next letter in the alphabet using PHP?

Answer

codaddict picture codaddict · Apr 20, 2010

The most efficient way of doing this in my opinion is to just increment the string variable.

$str = 'a';
echo ++$str; // prints 'b'

$str = 'z';
echo ++$str; // prints 'aa' 

As seen incrementing 'z' give 'aa' if you don't want this but instead want to reset to get an 'a' you can simply check the length of the resulting string and if its >1 reset it.

$ch = 'a';
$next_ch = ++$ch; 
if (strlen($next_ch) > 1) { // if you go beyond z or Z reset to a or A
 $next_ch = $next_ch[0];
}