Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Function To Get Character Number

Tags:

iteration

php

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 ?

like image 688
skos Avatar asked Jan 16 '13 12:01

skos


3 Answers

There is a function called ord which gives you the ASCII number of the character.

ord($chr) - ord('A') + 1

gives you the correct result for one character. For longer strings, you can use a loop.

<?php
    function GetCharacterNumber($str) {
        $num = 0;
        for ($i = 0; $i < strlen($str); $i++) {
            $num = 26 * $num + ord($str[$i]) - 64;
        }
        return $num;
    }
    GetCharacterNumber("A"); //1
    GetCharacterNumber("C"); //3
    GetCharacterNumber("Z"); //26
    GetCharacterNumber("AA"); //27
    GetCharacterNumber("AC"); //29
    GetCharacterNumber("BA"); //53
?>
like image 103
Dutow Avatar answered Oct 14 '22 06:10

Dutow


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

like image 34
Gordon Avatar answered Oct 14 '22 06:10

Gordon


Use range and strpos:

$letter = 'z';
$alphabet = range('a', 'z');
$position = strpos($alphabet, $letter);

For double letters (eg zz) you'd probably need to create your own alphabet using a custom function:

$alphabet = range('a', 'z');
$dictionary = range('a','z');
foreach($alphabet AS $a1){
    foreach($alphabet AS $a2) {
        $dictionary[] = $a1 . $a2;
    }
}

Then use $dictionary in place of $alphabet.

like image 32
Adam Hopkinson Avatar answered Oct 14 '22 04:10

Adam Hopkinson