settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Even and Odd Subtraction - PHP Task

+4 votes

Write a program that calculates the difference between the sum of the even and the sum of the odd numbers in an array.

Examples:

even and odd subtraction php task

asked in PHP category by user john7

2 Answers

+3 votes

Here is my solution:

<?php

$input = readline();

$arr = explode(' ', $input);

$even = 0;
$odd = 0;

foreach ($arr as $item) {
    if ($item % 2 == 0) {
        $even += $item;
    } else if ($item % 2 != 0) {
        $odd += $item;
    }
}

echo $even - $odd;
answered by user eiorgert
+2 votes

Hey, @eiorgert

Your input in one line can be:

$arr = array_map('intval', explode(' ', readline()));

 

answered by user Jolie Ann
...