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

Raju Kolte
Raju Kolte
3,110 Points

I don't no what is the answer but they shown me 6 anyone can explain this..

What does the following code display?

<?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 for loop looks at all the numbers in the numbers array. This means it will repeat anything within the block as many times as the array has entries. Then the value of i is set to i plus 1 After this there will be a check if the value of i is smaller than the value of total. If so, output will be number plus output pasted behid it ( not calculus +)

first run (1 out of 4) because the array has 4 entries) i = 0 -> becomes 1. is i (1) smaller than total(4) in this case i is smaller than total. output now becomes 1 (see number . output as -> numberoutput)

then the loop goes again through same process (run 2 out of 4) i = 1 -> becomes 2 i (2) is still smaller than total(4) output becomes number(2).output(1) -> 21

loop goes through process again (run 3 out of 4) i = 2 -> becomes 3 i(3) is still smaller than total(4) output becomes number(3).output(21) -> 321

loop goes through process one last time however i(4) is equal to total(4) so it stops

sorry for shit layout

1 Answer

Sergey Podgornyy
Sergey Podgornyy
20,660 Points

You don't need to compair it with counter, if you are using foreach loop. You just need:

<?php
$numbers = array(1,2,3,4);
$sum = 0;

foreach($numbers as $number) {
        $sum += $number;
}

echo $sum;
?>

In your case you receive 6, because you are using "Strict comparison" - less then (

 < 

), that's why your code first add counter and then compair if it less, then count of total elements in array.

In your case you can either use less equal then operator

$i = $i + 1;
    if ($i <= $total) {
        $sum = $sum + $number;
    }

or, put your counter under your comparisson:

    if ($i < $total) {
        $sum = $sum + $number;
    }
$i = $i + 1;

But I suggest you to use best practices, as I wrote above.