phpstringalphabet

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?


Solution

  • I could solve in this way. How is it? The cons is that it only can handle uppercase right now. Some more work can also fix that.

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