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 Bauer
9,426 PointsCan someone please help me understand foreach functions?
I got this problem on a quiz and the answer didn't make any sense to me.
$numbers = array(1,2,3,4); $total = count($numbers); $sum = 0; $loop = 0;
foreach($numbers as $number) { $loop = $loop + 1; if ($loop < $total) { $sum = $sum + $number; } }
echo $sum; //somehow the answer is 6.
1 Answer
richporter
16,727 PointsThe loop runs for each item in the array, so 4 times.
But on the last iteration of the loop, $loop is not less than $total (it is equal), so $sum isnt modified.
So 1 + 2 + 3 = 6
<?php
$numbers = array(1,2,3,4);
$total = count($numbers);
$sum = 0;
$loop = 0;
foreach($numbers as $number){
$loop = $loop + 1;
if ($loop < $total){
$sum = $sum + $number;
}
}
echo $sum;
Alex Bauer
9,426 PointsAlex Bauer
9,426 Pointsbut if $sum wasn't modified then wouldn't it still be 0? Also why wasn't 4 included when adding the numbers together in the array?
richporter
16,727 Pointsrichporter
16,727 Points$sum is modified on the 1st, 2nd and 3rd iteration of the loop.
1st time $sum is 0: 0 + 1
2nd time $sum is 1: 1 + 2
3rd time $sum is 3: 3 + 3
On the 4th iteration, $loop is not less than $total they are equal, so $sum isnt modified and the 4 is not added.
Alex Bauer
9,426 PointsAlex Bauer
9,426 PointsOkay! Now I finally understand thank you, this was a big help!