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 trialChloe Conn
3,217 PointsWHY!!
Why is the output to this 321?
<?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;
?>
3 Answers
Hayden Taylor
5,076 Pointsthe answer is 321 because output is treating it like a string. you are not adding the numbers like in the other quiz questions.
So what it is really doing is output = "3" . "2" . "1" where dot indicates a string concatenation.
Chloe Conn
3,217 Pointswhy does it start with the number three and not one?
Hayden Taylor
5,076 Pointsbecause you are always adding output to the end of the new string.
So first loop iteration is
Output = "1" . "" (output at the end of the string is empty because nothing is in it yet right?)
2) output = "2" . output (which is 1 from the previous iteration)
3) output = "3" . output (which is 2 1)
So again
1) output = 1 + "" 2) output = 2 + "1" 3) output = 3 + "21"
Hope this explains it better post a comment back if you are still having trouble.
Chloe Conn
3,217 PointsYes thank you so much!!! I understand now
Hayden Taylor
5,076 Pointsnp great! :)