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

Paul Yorde
Paul Yorde
10,497 Points

functions code challenge

How is this generating 6?

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

?>

1 Answer

Mike Costa
PLUS
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).