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

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;

?>

Choices: 10 - 6 - 1 - 123

My guess was 10 because they are adding $sum plus the $number instead of concatenating with the $output but I was wrong.

1 Answer

I'm going with 6 because on the final iteration $i=4 and $total=4. In order for the summation step to occur, $i must be less than $total but in the final iteration it's equal, so the code will not do the final addition.

So how did you come up with 6?

See the below

1 + 0 = 1 // $sum = 1
1 + 2 = 2 // $sum = 3
3 + 3 = 6 // $sum = 6

Because $i is incrementing by one number more every time the value of $i will be equal to 4 before the 4th index within the $numbers array is called.

ooohhhh I see ok so the value of $sum stores a new value for each time $i increments by 1 and adding that to each number in the array before it get's to 4