简体   繁体   中英

Converting alphabet letter to alphabet position in PHP

$my_alphabet = "T";

The above character "T" should print the exact position/number of the alphabet. ie 20

So, if

$my_alphabet = "A" ;
  • I should be able to get the position of the alphabet. ie 1

How can I achieve that.

I see converting number to alphabet .. but the reverse is not there anywhere.

Thanks, Kimz

By using the ascii value:

ord(strtoupper($letterOfAlphabet)) - ord('A') + 1

in ASCII the letters are sorted by alphabetic order, so...

In case the alphabet letter is not upper case, you can add this line of code to make sure you get the right position of the letter

$my_alphabet = strtoupper($my_alphabet);

so if you get either 'T' or 't' , it will always return the right position.

Otherwise @bwoebi 's answers will perfectly do the job

you should be careful about (uppercase, lowercase):

<?php
$upperArr = range('A', 'Z') ;
$LowerArr = range('a', 'z') ;
$myLetter = 't';

if(ctype_upper($myLetter)){
    echo (array_search($myLetter, $upperArr) + 1); 
}else{
    echo (array_search($myLetter, $LowerArr) + 1); 
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM