PHP Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Working with Functions

James Barrett
James Barrett
13,253 Points

Stuck on this question on a quiz?

Hi!

<?php

$numbers = array(1,2,3,4);

$total = count($numbers);

$sum = 0;

$output = "";

$i = 0;

foreach($numbers as $number) {

    $i = $i + 1;

    if ($i < $total) {

        $sum = $sum + $number;

    }

}

echo $sum;

?>

I am struggling as to why this outputs 6? Anyone mind walking through each step of this?

Thanks, James.

2 Answers

Benjamin Larson
Benjamin Larson
34,054 Points

Hi James,

The main part you want to focus on is:

    $i = $i + 1;

    if ($i < $total)

If the "less than" operator were changed to "less than or equal to", then the result would be 10. It's because the counter variable $i is being incremented before the conditional that adds to the sum. If the count increment were moved under the conditional block (as shown below), the end result would also be 10. Hope that helps some.

foreach($numbers as $number) {

    if ($i < $total) {

        $sum = $sum + $number;

    }

    $i = $i + 1;
}
John Lukacs
John Lukacs
26,210 Points

It only counts the first 3 numbers because the forth would add to four and 4 cannot be greater then 4 ($i < $total)