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 Simple PHP Application Working With Functions Working with Functions

jason taylor
jason taylor
2,455 Points

PHP Development Quiz 1 of 9

Hey all, I look at this code $output = $number . $output and all I see is 1.1 , 2.2, 3.3 How does it become 321? I realize it has to do with the concatenation but I can't get my head around it logically. Can someone dumb this down for me? Thanks in advance.

What does the following code display?

<?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;

?>

3 Answers

The dot in PHP can be used for string concatenation, e.g. "a"."b" => "ab"

Since $output persists, individual number just keeps getting appended in the front in the order they appear in the array (until $i gets too big).

At first, $output is empty ("")

Then, "1" is appended in front "1"."" => "1", so now $output is "1"

Then, "2" is appended in front "2"."1" => "21"

Then, "3" is appended in front "3"."21" => "321"

In the next loop, $i is now 4 after 1 is added to it, which is not less than $total, so nothing more gets appended.

Logan R
Logan R
22,989 Points

So you have your array: 1,2,3,4.

First off, the total is = 4, because it's counting how many numbers there are.

It loops through:

output = number . output

so 1:

null = 1 & null

1 = 2 & 1

21 = 3 & 21

so 321 is the answer because now i = 4 and 4 is not < 3.

Hope this helps out!

Just a correction, count() literally produces the count, so $total is actually 4, not 3.

Logan R
Logan R
22,989 Points

Good point John W, lol xD Sorry about that. I corrected it.

jason taylor
jason taylor
2,455 Points

Thanks for the responses guys. I kind of get it... I think I am just confused a bit by the concatenation. If it were simply $output = $number the answer would be 3 (not 123 because the echo happens AFTER the loop). I get that completely. But I guess where I get crazy is see that without the concatenation the answer is 3 so if I concatenate 3 to it I get 33. So somehow the concatenation tells it to hold onto the previous numbers. I`m sure it will make sense one day...