This forum is now read-only. Please use our new forums at discuss.codecademy.com.

While Loops in PHP Forum

View Course » View Exercise

2558 points
6ed491ee98d6f41061c68ef325974697?s=140&d=retro
Submitted by
likecoding777
over 4 years ago

An efficient way to add a variable $var into a string

In this 1.5 exercise it is said the following in the hint:

The syntax "StringStuff {$var} MoreStringStuff" is an efficient way to add a variable $var into a string.

<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$verb = "were";
$flipCount = 0;
$last = "flips";
echo "<p>There {$verb} {$flipCount} {$last}!</p>";
?>
</body>
</html>

Why is it efficient? I will prefer to NOT use the curly braces (i.e. instead of writing "{$verb}" only write "$verb"), but I don't know why the first one is more efficient.


7 votes

permalink

Dont know if this is an answer to your question but there is a debate that using double quoted strings is acctually less efficent than using single quotes.
Downside with using single quotes is that you need to concatenate with . and you will have alot more to type.

For example using single quote: (best performance)

echo '<p>There' . $verb . $flipCount . $last . '!</p>';

Double quotes: (bad performance)

 echo "<p>There $verb  $flipCount  $last !</p>";

Double quotes with curly: (good performance)

 echo "<p>There {$verb}  {$flipCount}  {$last} !</p>";

Now why its bad and good performance I really dont know. =) My guess is that PHP has to work little bit harder when using double quotes without curly. Use curly brackets and you cant go wrong.

Maybe an answer to your question -
http://stackoverflow.com/questions/4676417/should-i-use-curly-brackets-or-concatenate-variables-within-strings

Cheers

215 points
656d3ea01974ba12a8481d87f5163553?s=140&d=retro
Submitted by
Lidija Novakovic
over 4 years ago

1 Comment

6ed491ee98d6f41061c68ef325974697?s=140&d=retro likecoding777 over 4 years ago

Very good answer. I vote 1+ to it and if a "mark as best answer" button exists, I will mark this as the "best answer". Thanks.