Given any character from a to z, what is the most efficient way to get the next letter of the alphabet using PHP?
It depends on what you want to do when you click Z, but you have a few options:
$nextChar = chr(ord($currChar) + 1); // "a" -> "b", "z" -> "{"
You can also use PHP’s range() function:
range()
$chars = range('a', 'z'); // ['a', 'b', 'c', 'd', ...]
In my opinion, the most effective way is to only increase the string variable.
$str = 'a'; echo ++$str; // prints 'b' $str = 'z'; echo ++$str; // prints 'aa'
'a', incrementing 'z' will give 'aa' code> You can simply check the length of the resulting string and if it >1 resets it.
, incrementing
will give
code> You can simply check the length of the resulting string and if it
resets 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]; }
It depends on what you want to do when you click Z, but you have a few options:
You can also use PHP’s
range()
function:In my opinion, the most effective way is to only increase the string variable.
As you can see, if you don't want this but want to reset to get'a'
, incrementing
'z'will give
'aa'code> You can simply check the length of the resulting string and if it
>1resets it.