Reputation: 51
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.
A
is the first letter of the alphabet so it maps to 1
B
is the second letter of the alphabet so it maps to 2
C
is the third letter of the alphabet so it maps to 3
D
is the fourth letter of the alphabet so it maps to 4
So the word ABCD gives 1+2+3+4=10
Similarly I need a function for "testword" or any word.
Upvotes: 2
Views: 4456
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
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
Reputation: 3446
$a = "test";
$b = "word";
echo (strlen($a) + strlen($b));
Upvotes: -3