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

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;

?>