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 trialJames Barrett
13,253 PointsStuck on this question on a quiz?
Hi!
<?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;
?>
I am struggling as to why this outputs 6? Anyone mind walking through each step of this?
Thanks, James.
2 Answers
Benjamin Larson
34,055 PointsHi James,
The main part you want to focus on is:
$i = $i + 1;
if ($i < $total)
If the "less than" operator were changed to "less than or equal to", then the result would be 10. It's because the counter variable $i is being incremented before the conditional that adds to the sum. If the count increment were moved under the conditional block (as shown below), the end result would also be 10. Hope that helps some.
foreach($numbers as $number) {
if ($i < $total) {
$sum = $sum + $number;
}
$i = $i + 1;
}
John Lukacs
26,806 PointsIt only counts the first 3 numbers because the forth would add to four and 4 cannot be greater then 4 ($i < $total)