10
$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.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
user3350885
  • 739
  • 4
  • 16
  • 38

4 Answers4

28

By using the ascii value:

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

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

schellingerht
  • 5,726
  • 2
  • 28
  • 56
bwoebi
  • 23,637
  • 5
  • 58
  • 79
  • Even though the letters at location +1 each in ascii a problem arises if uppercase AND lowercase characters can be found as b is not ord(A)+1 but ord(a) +1. In that case either all letters need to be converted to uppercase or lowercsae (strtoupper, strtolower) OR it must be checked with ctype_upper if th letter is uppercase (then the solution from bwoebi) or if its lowercase then ord('a') instead of ord('A') has to be used. – Thomas May 14 '14 at 11:46
  • @ThomasE. or just use a `strtoupper()` < updated answer. – bwoebi May 14 '14 at 12:00
  • bwoebi -thanks .. this is what i want. excellent. saved my time. ;) – user3350885 May 14 '14 at 12:14
4

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

Community
  • 1
  • 1
Enjoyted
  • 1,131
  • 6
  • 15
4

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); 
}
?>
Mohammad Alabed
  • 809
  • 6
  • 17
0

if you use upper case and lower case use this function to get the right position

function offset(string $char): int {
  $abcUpper = range('A', 'Z');
  $abcLower = range('a', 'z');
  if (ctype_upper($char)) return array_search($char, $abcUpper) + 1;
  else return array_search($char, $abcLower) + 1;
}

test

echo offset("a"); // 1

if you use an array and you want to get the position to use in an array

function offset(string $char): int {
  $abcUpper = range('A', 'Z');
  $abcLower = range('a', 'z');
  if (ctype_upper($char)) return array_search($char, $abcUpper);
  else return array_search($char, $abcLower);
}

test

echo offset("a"); // 0