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 trialKenneth Hall
3,452 PointsHow 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.
3 Answers
Micah Kline
17,831 Points1 + 2 + 3 = 6
// move $i = $i + 1; to below your for loop
//---or
// change if ( $i < $total ) { to
if ( $i <= $total ) {
Greg Kaleka
39,021 PointsHi 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
3,452 PointsThanks 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
39,021 PointsAh gotcha - glad you got some clarity from Micah :)
Damien Watson
27,419 PointsDamien Watson
27,419 PointsIf 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)?