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

Cliff Jackson
Cliff Jackson
2,887 Points

Can someone explain how 6 is achieved in this code?

$numbers = array(1,2,3,4); $total = count($numbers); $sum = 0; $loop = 0;

foreach($numbers as $number) { $loop = $loop + 1; if ($loop < $total) { $sum = $sum + $number; } }

echo $sum;

2 Answers

Patrick Marshall
Patrick Marshall
13,508 Points

Hi Cliff,

Sometimes, when I get stuck on bugs like this I like to write out the steps in the code on paper. Going step by step through the code and writing down my results I get to see where I may have gone wrong. When I wrote yours out. get the following:

The for loop will run 4 times.  
The first time:
$number.=1, $total=4, $loop=1  -- $loop < $total, $sum = $sum(0) + $number(1) = 1.
The second time:
$number =2, $total=4, $loop=2 -- $loop < $total, $sum = $sum(1) + $number(2) = 3;
The third time:
$number=3, $total=4, $loop=3 --  $loop < $total, $sum = $sum(3) + $number(3) = 6;
The fourth time:
$number=4, $total=4, $loop=4 -- $loop == $total exit.

Hope this helps.

Cliff Jackson
Cliff Jackson
2,887 Points

Thanks for the reply but i still don't get this at all. the code is correct but i just don;t know how 6 is output.

Patrick Marshall
Patrick Marshall
13,508 Points

6 is output because on each loop you're adding $number to $sum. 1 + 2 + 3 = 6;