'Converting alphabet letter to alphabet position in PHP [duplicate]
$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.
Solution 1:[1]
By using the ascii value:
ord(strtoupper($letterOfAlphabet)) - ord('A') + 1
in ASCII the letters are sorted by alphabetic order, so...
Solution 2:[2]
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);
}
?>
Solution 3:[3]
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
Solution 4:[4]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | schellingerht |
Solution 2 | Mohammad Alabed |
Solution 3 | Community |
Solution 4 | Aly Ahmed Aly |