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.


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:
$addIn = "Something";

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

//How I've seen it
$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.