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

Ganho Kou
Ganho Kou
12,714 Points

I can't understand that result...

Hi, I really can't understand why this echo "321"?? I guess echo "123". But correct answer is "321"...

In "Building a Basic PHP Website"

<?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;

?>

please help...

1 Answer

Nathan Ward
Nathan Ward
7,907 Points

Hi,

The reason that the numbers are returned as '3,2,1' is because of $output is being concatenated to the end each time. So the first time the foreach loop runs it will output

1

The second loop will get the next number and then concatenate the previous number to the end for example:

2,1

And then again with the last number:

3,2,1

To get it to output the numbers in order you would need to do the following:

$output .= $number

I hope that helped you :)