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

PHP

Working with functions - Quiz: Understanding foreach loop function

Hi there,

Maybe I have a blond moment here, but I cannot get my head around on one of the quiz questions. The question is to tell, what will be the result of the following 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; ?>

The result which is correct, is "6", but I simply cannot comprehend this one. I'm getting only "5". Maybe I'm missing something? Here is what I would think this foreach loop is doing:

  1. loop $i = 0+1 = 1 1 < 4 = proceeding $sum = 0 + 1 = 1

  2. loop $i = 1+1 = 2 2 < 4 = proceeding $sum = 1 + 2 = 3

  3. loop $i = 2+1 = 3 3 < 4 = proceeding $sum = 3 + 2 = 5

  4. loop $i = 3+1 = 4 4 = 4 = not proceeding

End result: $sum = 5

What am I doing wrong here? Thanks for any enlightenment in advance! ;)

Cheers, Alex

3 Answers

The array has four items, starting with one. The $i = $i + 1; if ($i < $total) is just the counter, but the actual values to use for addition are in the array.

So the sum is ``0 + 1 (1st value of array) = 1 , 1 + 2 (2nd value of array) = 3 , 3 + 3 (3rd value of array) = 6 , 4 = not proceding

I remember too having a hard time with this, but the loops are like this.

  1. Loop $number = 1; $i = 0 + 1 = 1; $sum = 0 + $number = 1;

  2. Loop $number = 2; $i = 1 + 1 = 2; $sum = 1 + $number = 3;

  3. Loop $number = 3; $i = 2 + 1 = 3; $sum = 3 + $number = 6;

Thank you both! You really made my day. It just made "click"! ;) Cheers