Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Build a Simple PHP Application Adding a Contact Form Concatentation

Mike Zhu
Mike Zhu
1,840 Points

How to create a variable in PHP to be a set and hold the concatenation of three string variables

For example, the three variables are: $firstName = "Mike"; $middleName = "the"; $lastName = "Frog",

I want to create a variable called $fullName, how can I concatenate them with space between each variable?

3 Answers

Peter Hatzer
Peter Hatzer
20,837 Points

The above is best way that Gustavo Jose Morales Carpio showed you, but you could also do this, adding a spaces to the end of $firstName and $middleName it will give you the same answer:

$firstName = "Mike "; $middleName = "the "; $lastName = "Frog"

$fullname = $fisrtName . $middleName . $lastName;
Mike Zhu
Mike Zhu
1,840 Points

Thanks so much!! So, why can't I write like this? $fullName = $fullName.$firstName." ".$middleName." ".$lastName; I just get confused at what time should I write the $fullName again.

Peter Hatzer
Peter Hatzer
20,837 Points

$fullName is just a variable for storing info in, so when you echoing $fullName it will show you "Mike the Frog" because you added the 3 variables to $fullName, instead of you echoing each variable at a time. Variables store information so you can call on it in your script when you need them. hope this helps makes sense.

Simple way

```$fullname = $firstName . " " . $middleName . " " . $lastName;

Mike Zhu
Mike Zhu
1,840 Points

So, can I write like this? $fullName = $fullName.$firstName." ".$middleName." ".$lastName;

Hi Mike,

You don't need to write $fullname again, just write:

```$fullname = $firstName . " " . $middleName . " " . $lastName;