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.


Paul Yorde
Paul Yorde
10,497 Points

functions code challenge

How is this generating 6?


$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;


1 Answer

Mike Costa
Mike Costa
Courses Plus Student 26,362 Points

Hey Paul,

You're getting a sum of 6 because your $total variable is equal to 4, as there are 4 values in your $numbers array. In your if statement, when $i = 3, 3 is less than 4, so the first 3 values of $numbers gets added together, 1 + 2 + 3 = 6. If you want the last value accounted for, you can use

if($i <= $total) { $sum = $sum + $number; }

Hope that helps!

Paul Yorde
Paul Yorde
10,497 Points

I see. Each of the $numbers array gets put into the working variable $numbers. On the first iteration, $number + $sum = 1. On the second iteration, $sum = 3, and the final iteration is 6 (while 3 < 4).