4

My task is to create a loop that displays all even numbers in a column and it also displays a sum of all odd numbers in an array. So far I have made this:

<?php
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach ($numbers as $index=>$value) {
if ($value % 2 == 0)
echo "$value <br>";
}
?>

This code successfully displays a list of all even numbers. However, I still have to include a sum of all odd numbers that is displayed below the list of evens. For some reason, I am supposed to use a variable $sumOdd = 0.

How do I approach this from here on?

5 Answers 5

6
<?php
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$sumOdd = 0;

foreach ($numbers as $index=>$value) {

    if ($value % 2 == 0)
        echo "$value <br>";
    } else {
        $sumOdd += $value
    }
}

echo $sumOdd;
Sign up to request clarification or add additional context in comments.

1 Comment

Beat me to it nice
1

To do it backwards: add all numbers, take out the even ones

<?php
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$sum = array_sum($numbers);
foreach ($numbers as $index=>$value) {
  if ($value % 2 == 0)
  echo "$value <br>";
  $sum = $sum - $value;
}
echo 'odds: '. $sum;
?>

Comments

0

heyo,

the $sumOdd = 0; should be before the foreach, inside the foreach you will do another check and if it's odd you add the number on $sumOdd += $value

Comments

0

this is a short and cleaner answer :

$sumOdd = 0;

foreach (range(1, 10) as $number) {

    if (0 === $number % 2) {
        echo $number . '<br>';
        continue;
    } 

    $sumOdd += $number; 
}

echo '<br> sumOdd = '.$sumOdd;

2 Comments

This changes the entire snippet. Because of the nature of the question, i'm guessing the author doesn't have too much knowledge of PHP at this moment. Changing the snippets he wrote and understands, into something without explanation could confuse him even more. That's why i've only made minor changes to his snippet, instead of rewriting the whole thing.
thank you @JeroenBleijenberg, yeah i know, it's just to help him improve a little bit the way he write code. you're answer is what he needs ^^
0

A better way to calculate the sum is to pass the result of array_filter to array_sum. By doing that, you separate the tasks (calculate, display) and the code becomes more clean and maintainable.

$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$sumOdd = array_sum(array_filter($numbers, function($v) {
    return $v % 2 !== 0;
}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.