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

Leyla Varela
Leyla Varela
1,426 Points

Woking with Functions quiz question - can't figure out logic?

I think ok - so it's going to have to repeat up to 3 - sum = 0 + number. if it's a sum it's either 6 or 9 - I am unsure on whether it stating $i = $i + 1 means that it starts from 0 or 1?

*What does the following code display? *

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

?>

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

The answer is 6 and here is why. Keep in mind that during all of this the value for $total will only ever be equal to 4. So the first time through our loop, we start by setting $i to one. Then we ask if $i is less than 4. It is so we take sum (which is currently 0) and add the first number from our numbers array to it(which is 1). This gives sum the new value of 1.

The second time through the loop $i is now equal to $i + 1 (which is now 2) and yes that's still less than 4. So now we add the second number of the numbers array to the sum. Because the value of sum is still 1 and we add 2 we now have a running total of 3 assigned to sum.

The third time through the loop $i is now equal to $i + 1 (which is now 3) and it's still less than 4. We add the third number of the numbers array to the sum. So now we have 3 + 3 which gives sum a total of 6.

The fourth time through the loop $i will be equal to 4 and the if statement will fail because 4 is not less than 4. So our sum made it up to 6 before the loop exits.

Hope this clarifies things! :smile:

Leyla Varela
Leyla Varela
1,426 Points

Thanks Jennifer - definitely clarifies! The only thing is - when I clicked '6' as the answer it said it was wrong. Which is part of the reason I was so confused!