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

Can someone please explain the answer?

So the question I was on was asking "what will be the output".

<?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) {
        $output = $number . $output;
    }
}

echo $output;
?>

After getting the answer wrong I ran this in a PHP script so I know the answer is 321. However I can't understand why the answer is 321 instead of 123. I'm assuming it has something to do with this line: $output = $number . $output; But I don't know why, can someone please explain this to me. Thank you.

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! The trick here is the order of the concatenation that's happening in that line. If you had $output = $output . $number then "123" would have been echoed out.

Let's take a little closer look at what's happening.

The first time through the loop, $output starts as an empty string. Then we take the $number which is currently equal to 1 and concatenate an empty string onto it and assign it back into $output. But this has really no net effect other than now $output contains the string "1".

It's the second iteration that gets interesting. We're doing the same thing here but think about the order of how this is happening. We're taking our $number and concatenating the value in $output onto the end. We said $number is 2 and $output is 1. So 1 concatenated onto the end of 2 will result in "21". The "21" is assigned back into $output.

And this is the same thing that happens in the final iteration $number is equal to 3 and we're concatenating the value of $output onto the end. So 3 with "21" concatenated onto the end results in "321".

Hope this helps! :sparkles:

edited for example

// First iteration
// $output = 1 + ""
$output = $number . $output;

// Second iteration
// $output = 2 . "1"

// Third iteration
// $output = 3 . "21"

OK, I understand now why it's going 321 instead of 123. Thank you for answering my question.

Kedrick Martin
Kedrick Martin
8,243 Points

I still dont understand this,, i looked at this alot of times,, i still dont get whats going on.