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 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.