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 Basic PHP Website (2018) Adding a Basic Form Working with Concatenation and Whitespace

Pepe Suarez
Pepe Suarez
18,267 Points

Concatenation best practices

Hey Guys! I have been wondering for a while now why do we concatenate in PHP when we can echo a the variable inside a string? To make myself more clear let me do an example:

$name = "Mike";

echo "Hello $name";

echo "Hello " . $name;

Why do we use always use the second echo statement in PHP? Why don't we use the first one.... Thanks for the help but the doubt is killing me and I couldn't find anywhere an answer.

3 Answers

Chase Marchione
Chase Marchione
155,055 Points

In those cases it's more a matter of preference. Still, an advantage is that it can help with making code more immediately readable.

If you choose to continue as a PHP developer, you'll find yourself in situations in which it will be much more technically convenient to use the concatenation operator, but examples like the one you mentioned are probably more for the sake of familiarizing learners with the operator in and of itself.

The Build a Basic PHP Website course here at Treehouse provides a useful example of using the concatenation operator when building a string that involves the use of PHP in conjunction with retrieving data from HTML forms.

Interestingly (source: http://artprima.eu/925-string-variables-concatenation-vs-variable-interpolation.html)... the compiler tends to work faster with the non-concatenated approach.

jason chan
jason chan
31,009 Points

You'll learn templating engines later on which will make your life easier for html and php mangling on templates also known as views.

twig is an example: http://twig.sensiolabs.org/