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,820 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.