PHP Build a Basic PHP Website Listing and Sorting Inventory Items Creating the Display Function

Can someone explain why this code outputs 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;

?>

5 Answers

Simon Coates
Simon Coates
28,656 Points

the loop iterates with number being 1, then 2, then 3, then 4. The value i increases such that when number is four, the string concatenation is bypassed. So the loop is effectively just for when number is 1, 2, 3, add the number to the beginning of a string. So the string is "1", then "21", then "321".

"add the number to the beginning of a string". $output = $number . $output; I get that $number is one iteration. "$number . $output" looks like it would concatenate 1 with 2. 12 then 123. Obviously I'm missing something. I guess my question is what mechanism is causing the numbers to go to the beginning of the string instead of the usual sequence? And thank you for your help

Simon Coates
Simon Coates
28,656 Points

the use of $output = $number . $output; adds the value to the beginning of the string.

Simon Coates I didn't under when you said add the number to the beginning of a string. So the string is "1", then "21", then "321"" i am totally confused here.

Simon Coates
Simon Coates
28,656 Points

Ammar, the following code adds to the beginning:

$output = $number . $output;

as opposed to

$output = $output. $number;

Just substitute in the values as you go to see.

that was fast! Then my next question: is that a usual, common or practical thing to do? Or was it put in the quiz just to make me think?

Simon Coates
Simon Coates
28,656 Points

it was put in the quiz to ruin your life. It confuses everyone.

lol, thank you for that last comment. You made my night! and thank you again for your help :D

victor diaz
victor diaz
2,930 Points

oh that was a quiz! that sucks! :(

Hi victor, yea..when I come to something like that in a quiz I think: 1: did I miss something in the lesson? 2: that doesn't look even remotely familiar. 3: maybe I'm in over my head. At any given time any number of the above may be completely true or false.
Code on, never give up.

Cliff Jackson
Cliff Jackson
2,886 Points

Could not figure out how 321 was output on the screen and i still don't understand this

victor diaz
victor diaz
2,930 Points

Thank you very much John Larson, I really appreciate your answer. In fact I did that quiz with easy, but I find it stupidly intricate for no reason. Who in his senses would ever write that kind of code?