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 Simple PHP Application Working With Functions Working with Functions

Stephen Printup
seal-mask
.a{fill-rule:evenodd;}techdegree
Stephen Printup
UX Design Techdegree Student 45,252 Points

Stage 6, Working with functions: Confused

Hi,

I've passed the quiz, but I'm not sure how this works. Could someone please explain it to me?

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

?>

The options are: A-1234 B-4321 C-321 D-6

Hi Stephen,

Fixed markdown to show syntax highlighting. While you had the triple backticks, it was missing the php language specifier.

2 Answers

Hi Stephen,

The easiest way to work through these types of problems is with a sheet of paper, or text editor, to keep track of the values of variables through each iteration of the loop.

The short answer is that i gets incremented before it's checked against the length of the array. So, by the start of the 4th iteration of the loop, i == 4 and the if statement evaluates to false. Therefore, the only numbers that got added from the array are 1, 2, and 3.

Hope this helps!

Think of $total as just the number 4, and i starts at 0.

Loop iteration 1:
  i += 1
  i == 1
  i < 4 // True
    add current number (1) to sum (0)
    sum == 1

Loop iteration 2:
  i += 1
  i == 2
  i < 4 // True
    add current number (2) to sum (1)
    sum == 3

Loop iteration 3:
  i += 1
  i == 3
  i < 4 // True
    add current number (3) to sum (3)
    sum == 6

Loop iteration 4:
  i += 1
  i == 4
  i < 4 // False
    // sum remains at 6