PHP Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Working with Functions

Alex Herrera
PRO
Alex Herrera
Pro 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
PRO
Alex Herrera
Pro 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,054 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.