[Solved] Even and Odd Subtraction - PHP Task

  

4
Topic starter

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

2 Answers
3

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;
2

Hey, your input in one line can be:

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