Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

I really don't get how this is 6 (i ran it trough workspace) but don't understand how it got to this.

Sorry I am not getting this.

The answer is 6 (i ran it trough workspace) but don't understand how it got to this.

Julian Gutierrez
Julian Gutierrez
19,201 Points

Try going step by step, just a hint the answer is not 6.

Thank you for your reply

2 Answers

Are you referring to this function?

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

?>

Many thanks for helping out a newbie, I get it now!

If you were referring to the function I posted above this should help you have a better understanding of what is happening:

<?php

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

$total = count($numbers);
echo 'total = '. $total .'<br />';

$sum = 0;
echo 'sum = '. $sum .'<br />';

$output = "";

$i = 0;

foreach($numbers as $number) {

    $i = $i + 1;


    echo '$i = '. $i .'<br />';


    if ($i < $total) {

    echo 'When our condition is met $sum = '. $sum .' and $number = '. $number .'<br />';
        $sum = $sum + $number;

    }

}

echo $sum;

?>