Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,055 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)