Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Its working nicely:

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

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

Its very useful to get next column name in an excel file.

But if I use similar code using -- operator to get the previous letter then its not working:

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

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

What can be the solution to get the previous letter similarly? And what can be the reason as its not working?

like image 426
itsazzad Avatar asked Oct 14 '14 07:10

itsazzad


1 Answers

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

Note: This isn't circular for a-z. Need to add rules for that

Fiddle

Edit This edit covers for your special requirement from excel example. Although its a little longer piece of code.

//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

like image 123
Hanky Panky Avatar answered Oct 07 '22 01:10

Hanky Panky