Warning: session_start() [function.session-start]: open(/tmp/sess_0g705tff32abrdlocemikfk9n5, O_RDWR) failed: Disk quota exceeded (122) in /home/vipozico/forum.tutorials7.com/qa-include/qa-app-users.php on line 143
Character Multiplier - String Task
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Character Multiplier - String Task

+6 votes

Create a method that takes two strings as arguments and returns the sum of their character codes multiplied (multiply str1[0] with str2[0] and add to the total sum).

Then continue with the next two characters. If one of the strings is longer than the other, add the remaining character codes to the total sum without multiplication.


character multiplier string task

asked in PHP category by user sam

1 Answer

+5 votes

Nice task!

I've used this ASCII table:

ASCII table chars ascii values

and this is my code:


$args = explode(" ", readline());

$word1 = $args[0];
$word2 = $args[1];

$min = min(strlen($word1), strlen($word2));

$sum = 0;

for ($i = 0; $i < $min; $i++) {
    $code1 = ord($word1[$i]);//$word1: ASCII codes of the letters
    $code2 = ord($word2[$i]);//$word2: ASCII codes of the letters
    $sum += $code1 * $code2;

$remaining = '';

if (strlen($word2) > strlen($word1)) {
    $remaining = substr($word2, $min);
} else {
    $remaining = substr($word1, $min);

for ($i = 0; $i < strlen($remaining); $i++) {
    $code3 = ord($remaining[$i]);
    $sum += $code3;

echo $sum;
answered by user matthew44
edited by user golearnweb