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 trialAlex Herrera
Courses Plus Student 6,392 PointsConfused about PHP Function
The test says that this code will echo '6' True enough, when I run it on my local machine it does echo '6'.
But I dont know why!
<?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;
?>
In my head this should cycle through the loop 4 times, adding each value in the array to the variable $sum.
1+2+3+4 = 10
Clearly Im way off, can someone explain how we get to 6?
Thanks!
1 Answer
Alex Herrera
Courses Plus Student 6,392 PointsHang about, is this because 1 is added to $i at the start of the loop? So the loop only runs 3 times?
So, 1+2+3 = 6?
Benjamin Larson
34,055 PointsBenjamin Larson
34,055 PointsGuess you didn't need help after all :D Yes- adding 1 to
$i
means the loop only runs 3 times.You can always add some temporary echo statements to display the value of variables before, during or after loop iterations to try to gauge what's going on.