Viewed   116 times

Is it better to concatenate a variable (say, $name) into an existing string (say, $string) like this:

$string='Hi, my name is '.$name

or to embed the variable in the string like this:

$string="Hi, my name is $name";

or is it better to use a function like this:

$string=sprintf("Hi, my name is %s",$name);

Which is better in terms of processor time/efficiency?



Everyone who did the test concluded that using single quotes is marginally better performance wise. In the end single quotes result in just a concatenation while double quotes forces the interpreter to parse the complete string for variables.

However the added load in doing that is so small for the last versions of PHP that most of the time the conclusion is that it doesn't really matter.

So for the performance people: use single quotes. For the "i like my code readable"-people: double quotes are a lot better for the legibility, as Flavius Stef already pointed out.

Edit: One thing though - If you are going to use a a single dollar in your string without a variable, use single quotes for sure! ( points out that it will take 4 times longer to parse those strings)

Tuesday, November 15, 2022

Just use . for concatenating. And you missed out the $personCount increment!

while ($personCount < 10) {
    $result .= $personCount . ' people';

echo $result;
Thursday, September 22, 2022

The . operator is the concatenation operator. Your first example only works because the echo 'function' (technically it's a language construct, but lets not split hairs) accepts more than one parameter, and will print each one.

So your first example is calling echo with more than one parameter, and they are all being printed, vs. the second example where all the strings are being concatentated and that one big string is being printed.

Friday, September 9, 2022

It's perfectly fine. It's also the convention I use: single quotes for strings in EL. It's not only better readable, but it's also friendly for syntax highlighting.

Using double quotes is valid, but harder to interpret when nested in a HTML attribute which is by itself also double quoted.

Thursday, December 1, 2022

You could save that kind of string by modifying it on the server side before output, like this:

html_content = "<?=addslashes($string);?>"

The method addslashes($string) would then escape any double quotes at runtime before feeding it to the JavaScript variable.

Tuesday, September 20, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :