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!

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

General Discussion

13,877 Points

php function quiz explanation

So I just guessed that the answer to this question was 6 and it said I was correct, however, I have no idea how to figure that out. Can someone please explain this so it makes sense?

What does the following code display? <?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;


2 Answers

Tom Mertz
Tom Mertz
15,254 Points

Hey Matthew,

So you have an array called $numbers with 4 values - 1, 2, 3, 4. The variable $total stores the total elements in the array - 4; $output is never used, it's a distraction.

Once you get to the foreach loop you will go through the $numbers array grabbing 1 in the variable $number the first time, 2 the second, 3 the third and 4 the last time (until you have gone through the whole array).

Each time you go into the foreach loop you increase $i value by 1. So when $number = 1, $i = 0, then you add 1 to it and get 1, when $number = 2, $i = $i(1) + 1, which = 2. So on.

Remember, $total is 4 from the begin. Meaning that you will only add the value in $number to $sum when $i is 1, 2 or 3.

$sum starts as 0, when $number is 1, it is less than $total (4) so you add 1 to $sum and get $sum = 1;

$sum = 1, then $number = 2 (continuing through the foreach loop), is 2 less than 4? Yes, $sum = $sum(1) + $number(2).

$sum = 3, then $number = 3, is 3 less than 4? Yup, $sum = $sum(3) + $number(3).

$sum = 6, then $number = 4, is 4 less than 4? No, nothing happenings. Then there are no more numbers in the foreach loop to go through and we end it.

Next, you echo the value of $sum and it is right where you left it at 6!

Hope this helps,


13,877 Points

Thanks, Tom! Wow, yes, it makes perfect sense now! Big Help! Earned the badge on the next try!

Tom Mertz
Tom Mertz
15,254 Points

Glad to hear it :)