Simran
Simran

Reputation: 51

How can I calculate the sum of "letter numbers" in a string?

Is there any built-in PHP function through which I can count the sum of indexes of letters of the alphabet found in a string?

<?php
$a = "testword";
echo "Count of Characters is: " . strlen($a); 
?>

Now I want to get a cumulative "total" of this word.

e.g.

So the word ABCD gives 1+2+3+4=10

Similarly I need a function for "testword" or any word.

Upvotes: 2

Views: 4456

Answers (3)

Mark Baker
Mark Baker

Reputation: 212412

Just to show a totally different method, for the sheer pleasure of demonstrating some of PHP's array functions:

$data = "testword";

$testResult = array_values(array_merge(array_fill_keys(range('A','Z'),
                                                       0
                                                      ),
                                       array_count_values(str_split(strtoupper($data)
                                                                   )
                                                         )
                                      )
                          );
$wordCount = 0;
foreach($testResult as $letterValue => $letterCount) {
    $wordCount += ++$letterValue * $letterCount;
}

var_dump($wordCount);

Upvotes: 0

craig1231
craig1231

Reputation: 3867

function WordSum($word)
{
    $cnt = 0;
    $word = strtoupper(trim($word));
    $len = strlen($word);

    for($i = 0; $i < $len; $i++)
    {
        $cnt += ord($word[$i]) - 64; 
    }

    return $cnt;
}

var_dump(WordSum("testword"));

Upvotes: 9

Bart Vangeneugden
Bart Vangeneugden

Reputation: 3446

$a = "test";
$b = "word";
echo (strlen($a) + strlen($b));

Upvotes: -3

Related Questions