Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting alphabet letter to alphabet position in PHP

Tags:

php

$my_alphabet = "T";

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

So, if

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

How can I achieve that.

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

like image 383
user3350885 Avatar asked May 14 '14 11:05

user3350885


3 Answers

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); 
}
?>
like image 106
Mohammad Alabed Avatar answered Nov 08 '22 13:11

Mohammad Alabed


By using the ascii value:

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

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

like image 33
bwoebi Avatar answered Nov 08 '22 13:11

bwoebi


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

like image 40
Enjoyted Avatar answered Nov 08 '22 12:11

Enjoyted