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?
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With