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 trialKireeti K
9,675 Pointswhat is the output of this program?
<?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) {
$output = $number . $output;
}
}
echo $output;
?>
I assume the output is 1234 and my explanation is as follows
$output is null while declaring it and hence
$output = 1.NULL; 1st iteration $output is now 1 $output = 1.2; 2nd iteration $output is now 12 $output = 12.3; 3rd iteration $output is now 123 $output = 123.4; last iteration $output is now 1234
If condition Fails..
While answering the quiz i got bummer for 1234, Please correct me where did i go wrong and what is the output
Thanks!
4 Answers
Kireeti K
9,675 PointsFinally Understood..
i is set to 1 so it only loops 3 times and i concatenated the wrong way.. The answer is 321
Kireeti K
9,675 PointsHello Simon, Thanks for the reply. Sorry but i dont understand can you please elaborate..
Simon Coates
28,694 PointsWith code, there's a tendency to see what you think it should mean. so people look at $output = $number . $output; and think $output = $output. $number; People expect to see 1234, more than 321.
Kireeti K
9,675 PointsYes :)
Simon Coates
28,694 PointsSimon Coates
28,694 PointsA couple people have been thrown by that one. you get so used to thinking $variableName = variableName... or the compound operator syntax (+= etc), that you seen what you expect to see.