Welcome to the Treehouse Community
Looking to learn something new?
J Scott Erickson11,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 (.) ?
Casey Ydenberg15,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.