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 foreach

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

I just took the quiz right here, I think the result should be 10, but why the result is 6?

Hope someone can tell me the detail, thank you so much!

Justin Barrett
Justin Barrett
27,243 Points

in your pass: //first pass, loop = 1, if(1 < 4){sum = 0 + 1}, sum = 1 //second pass loop = 2, if(2 < 4) {sum = 2+2;}, sum = 3 //third pass loop = 3, if(3 < 4), {sum = 3+3;}, sum = 6 //fourth pass loop = 4, if(4 < 4), false, sum still equals 6

if you were to change to if ($loop <= $total), then the fourth pass would be true and your sum would equal 10.

//revised fourth pass loop = 4, if(4 <= 4), {sum = 6+4;}, sum = 10

Thank you for your help. So, what if there is no $loop variable at here, then there is only one value will pass to the $sum variable?