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

Kenneth Hall
Kenneth Hall
3,452 Points

How is this equaling 6?

Hello everyone,

In a test I came across a question that asks, "what does the following code output?"

<?php

$numbers = array (1 , 2 , 3 , 4 );

$total = count ( $numbers );

$sum = 0;

$output = "";

foreach( $numbers as $number ) {

$i = $i + 1;

if  ( $i < $total ) {

    $sum = $sum + $number;

}

}

$i = 0;

echo $sum;

?>

Could anyone explain to me how this is getting the equaling 6? Thanks so much in advance for any info. This has got me stumped.

Damien Watson
Damien Watson
27,419 Points

If it's working correctly, looks like $sum should be 10. It doesn't look like $i is initialised outside of the foreach loop, if $i started at 1, then it would only through the first 3 numbers ($sum = 6)?

3 Answers

1 + 2 + 3 = 6

// move $i = $i + 1; to below your for loop 
//---or
// change if  ( $i < $total ) { to

if  ( $i <= $total ) { 
Greg Kaleka
Greg Kaleka
39,018 Points

Hi Kenneth,

There are a few problems with your code.

First, you need to initialize $i before you start checking its value.

Second, the if statement is stopping before you go through it the 4th time, because $total is equal to 4. You could change your < to <=.

However, I would probably drop the $i and if statement altogether. A foreach loop will do this incrementing for you. Here's what I'd write:

<?php

$numbers = array (1 , 2 , 3 , 4 );

$sum = 0;

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

echo $sum;

?>

Hope this helps!

Greg

Kenneth Hall
Kenneth Hall
3,452 Points

Thanks Micah!

That makes sense now. I wasn't seeing how they were getting that number.

Greg,

It was a question straight from the "working with functions" test on here. I just wasn't how they were getting the outcome of 6.

Greg Kaleka
Greg Kaleka
39,018 Points

Ah gotcha - glad you got some clarity from Micah :)