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 trialAdi Perdana Arifin
328 PointsCan you help me to explain how the logic works in this question?
I was answering 10, but I got wrong. May I know what is the correct answer?
1 Answer
Jennifer Nordell
Treehouse TeacherHi there! I believe you may be referring to the question in regards to this code:
<?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;
?>
Let's see if we can break this down. $total will always equal 4 as it's the number of elements we have in our array. We start through the array with $i being equal to 0. And we get the number at the index of 0 which is 1. We add that to sum. So sum is now 1.
Our second iteration $i is equal to 2. This is less than 4 so we add the second element 2 to sum. Our sum is now 3.
Our third iteration $i is equal to 3. This is less than 4 so we add the third element 3 to sum. Our sum is now 6.
Our fourth iteration $i is equal 4. Four is not less than 4 so this fails and nothing else will be added to sum.
The resulting sum echoed out will be 6.
Hope this helps!
Adi Perdana Arifin
328 PointsAdi Perdana Arifin
328 PointsThank you so much for the answer, very helpful.