0

I want to make someting like-

A  = 1
B  = 2
...
...
Z  = 26
AA = 27
AB = 28
AC = 29

I used ASCII code converter and range function to do that. But didn't worked. In this case.

<?php
    $range = range('AA','ZZ');
    print_r($range);
?>

// Returns an array A to Z not AA to ZZ

So, Is there any possible way to do that?

JaTurna
  • 194
  • 14

4 Answers4

2

You can use the fact that incrementing a string using ++ will wrap around back to AA once it reaches Z, and so on from there:

<?php
$result = [];
$string = 'A';

for ($i = 1; $i <= 26*27; $i++) {
  $result[$string] = $i;
  $string++;
}

=

Array
(
    [A] => 1
    [B] => 2
    [C] => 3
    [D] => 4
    [E] => 5
    ...

See https://eval.in/825359

iainn
  • 16,826
  • 9
  • 33
  • 40
  • I think you'll need `26 * 27` rows; number of letters in the alphabet squared for `AA --> ZZ` *plus* `A --> Z` – CD001 Jun 30 '17 at 15:48
  • Good point, edited. I should have paid more attention to the output... – iainn Jun 30 '17 at 15:49
2

Here's something that works by using range to assign a value [0,25] to each letter by way of an array index. Then add one extra and you're good. The downside is that this won't work for something like AZA but you said you only need 2 letters.

    $string = 'ZZ';
    $result = 0;
    foreach (str_split(strtolower($string)) as $letter) {
        $result += array_search($letter, range('a', 'z')) + 1;
    }
    print($result);
Mike
  • 346
  • 2
  • 8
0

You could assign a value to all letters. Then convert the string into an array so that each value in the array is a letter. Then loop over the array, and sum all of the array elements based on the value of the letter.

Teun
  • 916
  • 5
  • 13
0
<?php
$test = "AA";
$ascval = array_map('ord', str_split($test));
var_dump(implode("", $ascval));
var_dump(array_sum($ascval));

Yields:

string(4) "6565"
int(130)

http://sandbox.onlinephpfunctions.com/code/ceb1fa2e8cb29c9f9dbf5e6c30db9878941e34ad

Matt
  • 5,315
  • 1
  • 30
  • 57