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 Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Working with Functions

tomas jucevicius
tomas jucevicius
2,130 Points

Why numbers came in $output different order, not 123 but 321?

I know that 321 is the right answer, i checked it in code editor , but what i want to know why this number is not 123, why numbers are in backwards.

1 Answer

Dave StSomeWhere
Dave StSomeWhere
19,870 Points

I think the purpose of the question is getting you in the practice of walking through code.

Please see comments in the code below:

<?php
$numbers = array(1, 2, 3, 4);
$total = count($numbers);
$sum = 0;
$output = "";
$loop = 0;

foreach ($numbers as $number) {
    $loop = $loop + 1;
    if ($loop < $total) { // count numbers = 4, loop starts = 1, loop runs 3 times.
        $output = $number . $output;
        // loop 1 - concat 1 with "" - result 1.
        // loop 2 - concat 2 with 1 - result 21.
        // loop 3 - concat 3 with 21 - result 321.
    }
}

echo $output;
?>

make sense?

tomas jucevicius
tomas jucevicius
2,130 Points

Thank you Dave, My mistake was that I forgot about concat order.