Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 781
Mathias Bynens Avatar asked Apr 20 '10 07:04

Mathias Bynens


People also ask

How do you find a letter in a string PHP?

The strpos() function finds the position of the first occurrence of a string inside another string. Note: The strpos() function is case-sensitive. Note: This function is binary-safe.

How do I get the first letter of a word in PHP?

So you can easily use $i[0] to fetch first letter.

How do you get the next letter in JavaScript?

To get the next letter of the alphabet in JavaScript, we can use the String. fromCharCode static string method and the charCodeAt string instance method.


1 Answers

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]; } 
like image 157
codaddict Avatar answered Sep 23 '22 11:09

codaddict