The most efficient way to get the previous letter in the alphabet using PHP

It works well :

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

It is very useful to get the following column name in an excel file.

But if I use the same code using the operator - to get the previous letter, then it doesn't work:

 $str = 'b'; echo --$str; // prints 'b' but I need 'a' $str = 'aa'; echo --$str; // prints 'aa' but I need 'z' 

What could be the decision to receive the previous letter in the same way? And what could be the reason for its inoperability?

+8
string php
source share
3 answers

I could decide that way. How is it? The disadvantages are that it can only handle upper case right now. Another work can also fix this.

 <?php function get_previous_letter($string){ $last = substr($string, -1); $part=substr($string, 0, -1); if(strtoupper($last)=='A'){ $l = substr($part, -1); if($l=='A'){ return substr($part, 0, -1)."Z"; } return $part.chr(ord($l)-1); }else{ return $part.chr(ord($last)-1); } } echo get_previous_letter("AAAAAA"); ?> 

CODEPAD

-one
source share
 $str='z'; echo chr(ord($str)-1); //y 

Note. This is not circular for az . You must add rules for this.

Fiddle

Edit This edit covers your particular excel requirement. Although its a bit longer code snippet.

 //Step 1: Build your range; We cant just go about every character in every language. $x='a'; while($x!='zz') // of course you can take that to zzz or beyond etc { $values[]=$x++; // A simple range() call will not work for multiple characters } $values[]=$x; // Now this array contains range `a - zz` //Step 2: Provide reference $str='ab'; //Step 3: Move next or back echo $values[array_search(strtolower($str),$values)-1]; // Previous = aa echo $values[array_search(strtolower($str),$values)+1]; // Next = ac 

Fiddle

+5
source share

Using an array:

 $cla=array('A', 'B', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'Š', 'Z', 'Ž', 'T', 'U', 'V', 'Õ', 'Ä', 'Ö', 'Ü'); $direction = -1; $element = 'Ü'; $element2 = $cla[((array_search($element,$cla)+count($cla)+$direction)%count($cla))]; 
0
source share

All Articles