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

Can you help me to explain how the logic works in this question?

I was answering 10, but I got wrong. May I know what is the correct answer?

1 Answer

Jennifer Nordell
Jennifer Nordell
Treehouse Teacher

Hi there! I believe you may be referring to the question in regards to this code:

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

Let's see if we can break this down. $total will always equal 4 as it's the number of elements we have in our array. We start through the array with $i being equal to 0. And we get the number at the index of 0 which is 1. We add that to sum. So sum is now 1.

Our second iteration $i is equal to 2. This is less than 4 so we add the second element 2 to sum. Our sum is now 3.

Our third iteration $i is equal to 3. This is less than 4 so we add the third element 3 to sum. Our sum is now 6.

Our fourth iteration $i is equal 4. Four is not less than 4 so this fails and nothing else will be added to sum.

The resulting sum echoed out will be 6.

Hope this helps! :sparkles:

Thank you so much for the answer, very helpful.