Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

Alex Bauer
Alex Bauer
9,426 Points

Can 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

The 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
Alex Bauer
9,426 Points

but 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?

$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
Alex Bauer
9,426 Points

Okay! Now I finally understand thank you, this was a big help!