###### john larson

16,593 Points# 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

28,677 Pointsthe 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".

###### john larson

16,593 Pointsthat 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

28,677 Pointsit was put in the quiz to ruin your life. It confuses everyone.

###### john larson

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

###### victor diaz

2,930 Pointsoh that was a quiz! that sucks! :(

###### john larson

16,593 PointsHi 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

2,886 PointsCould not figure out how 321 was output on the screen and i still don't understand this

###### victor diaz

2,930 PointsThank 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?

## john larson

16,593 Points## john larson

16,593 Points"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

28,677 Points## Simon Coates

28,677 Pointsthe use of $output = $number . $output; adds the value to the beginning of the string.

## ammarkhan

Front End Web DevelopmentTechdegree Student 21,661 Points## ammarkhan

Front End Web DevelopmentTechdegree Student 21,661 PointsSimon 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

28,677 Points## Simon Coates

28,677 PointsAmmar, 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.