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 trialStephen Printup
UX Design Techdegree Student 45,252 PointsStage 6, Working with functions: Confused
Hi,
I've passed the quiz, but I'm not sure how this works. Could someone please explain it to me?
<?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;
?>
The options are: A-1234 B-4321 C-321 D-6
2 Answers
Robert Richey
Courses Plus Student 16,352 PointsHi Stephen,
The easiest way to work through these types of problems is with a sheet of paper, or text editor, to keep track of the values of variables through each iteration of the loop.
The short answer is that i
gets incremented before it's checked against the length of the array. So, by the start of the 4th iteration of the loop, i == 4
and the if statement evaluates to false. Therefore, the only numbers that got added from the array are 1, 2, and 3.
Hope this helps!
Robert Richey
Courses Plus Student 16,352 PointsThink of $total
as just the number 4, and i
starts at 0.
Loop iteration 1:
i += 1
i == 1
i < 4 // True
add current number (1) to sum (0)
sum == 1
Loop iteration 2:
i += 1
i == 2
i < 4 // True
add current number (2) to sum (1)
sum == 3
Loop iteration 3:
i += 1
i == 3
i < 4 // True
add current number (3) to sum (3)
sum == 6
Loop iteration 4:
i += 1
i == 4
i < 4 // False
// sum remains at 6
Stephen Printup
UX Design Techdegree Student 45,252 PointsThank you, that explains a lot. I thought it was something like that, but the way you explained it helped.
Robert Richey
Courses Plus Student 16,352 PointsRobert Richey
Courses Plus Student 16,352 PointsHi Stephen,
Fixed markdown to show syntax highlighting. While you had the triple backticks, it was missing the php language specifier.