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 trialRobert Engelbert
7,229 PointsPlease explain
I keep going over this on a php quiz and I'm stumped. How do they get that answer?
<?php
$numbers = array(1,2,3,4);
// $total should hold the value of 4
$total = count($numbers);
$sum = 0;
$output = "";
$i = 0;
foreach($numbers as $number) {
$i = $i + 1;
//so we iterate through the loop 4 times
if ($i < $total) {
//if 0 = 0 + 4 shouldn't we get 4?
$sum = $sum + $number;
}
}
echo $sum;
?>
The answer is 6
2 Answers
Jennifer Nordell
Treehouse TeacherHi there! You're correct in saying the loop executes 4 times. But in reality, the if statement inside the loop only executes 3 times. On the last pass, i
will be equal to 4 which means that i
will not be less than $total
. So the $sum
will only ever have the 1, 2, and 3 added together. Let's take it step for step.
On the first pass the number will be equal to 1. The variable i is incremented to 1. Because i is less than 4, 1 is added to the running total.
On the second pass the number will be equal to 2. The variable i is incremented to 2. Because 2 is less than four, 2 is added to the running total giving us a result of 3.
On the third pass the number will be equal to 3. The variable i is incremented to 3. Because 3 is less than four, 3 is added to the running total giving us a result of 6.
On the fourth pass the number will be equal to 4. The variable is incremented to 4. Because 4 is not less than 4 the code inside this if statement is never executed. Our running total remains at 6.
Hope this clarifies things!
Kevin Korte
28,149 PointsYes, in this case $sum
would equal 6, but if this is the quiz I think it is, I thought it was a bit different. Is this the same question?
https://teamtreehouse.com/community/what-does-this-mean-output-number-output
Robert Engelbert
7,229 PointsThe question you linked to is in the same quiz, but not the same question.
Kevin Korte
28,149 PointsGottcha, okay. Wasn't sure exactly where to find it to check myself. Glad you got it sorted out. Cheers!
Robert Engelbert
7,229 PointsRobert Engelbert
7,229 PointsThank you Jennifer, I get it now. Things should start making sense now.