PHP Function To Get Character Number

iteration, php

Solution

Not very efficient but gets the job done:

function get_character_number($end) 
{
    $count = 1;
    $char = 'A';
    $end = strtoupper($end);
    while ($char !== $end) {
        $count++;
        $char++;
    }
    return $count;
}

echo get_character_number('AA'); // 27

demo

This works because when you got something like `$char = 'A'` and do `$char++`, it will change to 'B', then 'C', 'D', … 'Z', 'AA', 'AB' and so on.

Note that this will become the slower the longer `$end` is. I would not recommend this for anything beyond 'ZZZZ' (475254 iterations) or if you need many lookups like that.

An better performing alternative would be

function get_character_number($string) {
    $number = 0;
    $string = strtoupper($string);
    $dictionary = array_combine(range('A', 'Z'), range(1, 26));
    for ($pos = 0; isset($string[$pos]); $pos++) {
        $number += $dictionary[$string[$pos]] + $pos * 26 - $pos;
    }
    return $number;
}

echo get_character_number(''), PHP_EOL; // 0
echo get_character_number('Z'), PHP_EOL; // 26
echo get_character_number('AA'), PHP_EOL; // 27

demo

Problem

How can I write a function that gives me number of the character that is passed to it For example, if the funciton name is `GetCharacterNumber` and I pass `B` to it then it should give me `2` ``` GetCharacterNumber("A") // should print 1 GetCharacterNumber("C") // should print 3 GetCharacterNumber("Z") // should print 26 GetCharacterNumber("AA") // should print 27 GetCharacterNumber("AA") // should print 27 GetCharacterNumber("AC") // should print 29 ``` Is it even possible to achieve this ?

Original source