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
Lucas Santos
19,315 PointsWhat does the following code display?
<?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;
?>
Choices: 10 - 6 - 1 - 123
My guess was 10 because they are adding $sum plus the $number instead of concatenating with the $output but I was wrong.
1 Answer
Erin Olmon
2,271 PointsI'm going with 6 because on the final iteration $i=4 and $total=4. In order for the summation step to occur, $i must be less than $total but in the final iteration it's equal, so the code will not do the final addition.
Lucas Santos
19,315 PointsLucas Santos
19,315 PointsSo how did you come up with 6?
Chris Shaw
26,676 PointsChris Shaw
26,676 PointsSee the below
Because
$iis incrementing by one number more every time the value of$iwill be equal to 4 before the 4th index within the$numbersarray is called.Lucas Santos
19,315 PointsLucas Santos
19,315 Pointsooohhhh I see ok so the value of $sum stores a new value for each time $i increments by 1 and adding that to each number in the array before it get's to 4