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

J Scott Erickson
J Scott Erickson
11,883 Points

Variable Usage In Strings

I haven't finished the PHP track yet, but I'm curious as to a difference I see between the way that Treehouse says to handle variable concat in a string and how I've seen it done in my workplace.

// The treehouse way:
<?php
$addIn = "Something";

echo "This is a string with " . $addIn . "added in.";
?>

//How I've seen it
<?php 
$addIn = "Something"

echo "This is a string with $Something added in.";
?>

So.... Is there some reason why this would not work? Or is it considered a best practice to use the concat operator (.) ?

1 Answer

Casey Ydenberg
Casey Ydenberg
15,622 Points

There are lots of different ways of doing it. Most important thing: double quotes strings may contain variables, single quoted strings must not.

One slight advantage to using concatenation is that, when reading single quotes, the PHP parser does not have to look through the string to see if there are any variables, which results in a performance increase. Putting the variables directly into the string can be easier to read, but remember that HTML contains a lot of double quotes, which you will then have to escape. There are other solutions like sprintf, heredocs, and "dropping out" of PHP altogether. The choice of which one to use depends on the situation and the standards of your organization/project.