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
Don Shipley
19,488 PointsPHP
Why does it reverse the numbers to 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;
?>
2 Answers
Aaron Graham
18,033 Pointsbecause of '$output = $number . $output'. Basically
- the first iteration of the loop gives you '$output = $number' which is 1
- the second iteration gives you '$output = $number . $output' which is 2 . 1 The new number is being concatenated to the front of your output buffer. You could change the order by making it '$output = $output . $number'
Jeffrey Wambugu
8,548 PointsHi, in the if statement, you are concatenating the first number behind the second one. that is when the first number (1) $output = 1; then concatenate the second (2) one after that so $output = 21; then concatenate the third(3) one after that so $output = 321;
If you want it to be 123 then use
$output = $output . $number;