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 Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Working with Functions

Alex Herrera
PLUS
Alex Herrera
Courses Plus Student 6,392 Points

Confused about PHP Function

The test says that this code will echo '6' True enough, when I run it on my local machine it does echo '6'.

But I dont know why!

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

?>

In my head this should cycle through the loop 4 times, adding each value in the array to the variable $sum.

1+2+3+4 = 10

Clearly Im way off, can someone explain how we get to 6?

Thanks!

1 Answer

Alex Herrera
PLUS
Alex Herrera
Courses Plus Student 6,392 Points

Hang about, is this because 1 is added to $i at the start of the loop? So the loop only runs 3 times?

So, 1+2+3 = 6?

Benjamin Larson
Benjamin Larson
34,055 Points

Guess you didn't need help after all :D Yes- adding 1 to $i means the loop only runs 3 times.

You can always add some temporary echo statements to display the value of variables before, during or after loop iterations to try to gauge what's going on.