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

PHP

problem with understanding php Quiz - section : working with function

What does the following code display? <?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;

?>

Can anyone explain how this piece of code echo out "321" instead of "123"

2 Answers

The $output = $number . $output; statement prepends each number to the output string, i.e. In the first foreach cycle, $output = "1" ($number = 1, $output = "") In the second, $output = "21" ($number = 2, $output ="1") In the third, $output = "321" ($number = 3, $output = "21") etc

To echo 123, the statement should have been $output = $output . $number;

Thanks so much now I get it .