Home  >  Q&A  >  body text

PHP: Maximize efficiency in finding next letter

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

P粉718730956P粉718730956339 days ago539

reply all(2)I'll reply

  • P粉616383625

    P粉6163836252023-10-20 12:44:44

    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:

    $chars = range('a', 'z');  // ['a', 'b', 'c', 'd', ...]

    reply
    0
  • P粉216203545

    P粉2162035452023-10-20 10:07:40

    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'

    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 >1 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];
    }

    reply
    0
  • Cancelreply