[php] PHP - concatenate or directly insert variables in string

I am wondering, What is the proper way for inserting PHP variables into a string?

This way:

echo "Welcome ".$name."!"

Or this way:

echo "Welcome $name!"

Both of these methods work in my PHP v5.3.5. The latter is shorter and simpler but I'm not sure if the first is better formatting or accepted as more proper.

This question is related to php string variables concatenation

The answer is


You Should choose the first one. They have no difference except the performance the first one will be the fast in the comparison of second one.

If the variable inside the double quote PHP take time to parse variable.

Check out this Single quotes or double quotes for variable concatenation?

This is another example Is there a performance benefit single quote vs double quote in php?

I did not understand why this answer in above link get upvoted and why this answer got downvote.

As I said same thing.

You can look at here as well

What is faster in PHP, single or double quotes?


Double-quoted strings are more elegant because you don't have to break up your string every time you need to insert a variable (like you must do with single-quoted strings).

However, if you need to insert the return value of a function, this cannot be inserted into a double-quoted string--even if you surround it with braces!

//syntax error!!
//$s = "Hello {trim($world)}!"

//the only option
$s = "Hello " . trim($world) . "!";

If you want to execute a SQL command and your variables are array members, then you should not use single quotes inside [] of array (like this: ['']); for example if you use this string as a SQL command, you get server error 500:

$con = mysqli_connect('ServerName', 'dbUsername', 'dbPassword');
mysqli_select_db($con, 'dbName')

//'ID' is auto increment field.
$sql = "INSERT INTO sampleTable (ID, TraceNo) VALUES ('','$sampleArray['TraceNo']')";
mysqli_query($con, $sql)

The correct string is:

//'ID' is auto increment field.
$sql = "INSERT INTO sampleTable (ID, TraceNo) VALUES ('','$sampleArray[TraceNo]')";

I know this question already has a chosen answer, but I found this article that evidently shows that string interpolation works faster than concatenation. It might be helpful for those who are still in doubt.


Either one is fine. Use the one that has better visibility for you. And speaking of visibility you can also check out printf.


From the point of view of making thinks simple, readable, consistent and easy to understand (since performance doesn't matter here):

  • Using embedded vars in double quotes can lead to complex and confusing situations when you want to embed object properties, multidimentional arrays etc. That is, generally when reading embedded vars, you cannot be instantly 100% sure of the final behavior of what you are reading.

  • You frequently need add crutches such as {} and \, which IMO adds confusion and makes concatenation readability nearly equivalent, if not better.

  • As soon as you need to wrap a function call around the var, for example htmlspecialchars($var), you have to switch to concatenation.

  • AFAIK, you cannot embed constants.

In some specific cases, "double quotes with vars embedding" can be useful, but generally speaking, I would go for concatenation (using single or double quotes when convenient)


I use a dot(.) to concate string and variable. like this-

echo "Hello ".$var;

Sometimes, I use curly braces to concate string and variable that looks like this-

echo "Hello {$var}";

I prefer this all the time and found it much easier.

echo "Welcome {$name}!"

Since php4 you can use a string formater:

$num = 5;
$word = 'banana';
$format = 'can you say %d times the word %s';
echo sprintf($format, $num, $word);

Source: sprintf()


It only matter of taste.
Use whatever you wish.

Most of time I am using second one but it depends.

Let me suggest you also to get yourself a good editor which will highlight a variable inside of a string


Go with the first and use single quotes!

  1. It's easier to read, meaning other programmers will know what's happening
  2. It works slightly faster, the way opcodes are created when PHP dissects your source code, it's basically gonna do that anyway, so give it a helping hand!
  3. If you also use single quotes instead of double quotes you'll boost your performance even more.

The only situations when you should use double quotes, is when you need \r, \n, \t! The overhead is just not worth it to use it in any other case.

You should also check PHP variable concatenation, phpbench.com for some benchmarks on different methods of doing things.


Do not concatenate. It's not needed, us commas as echo can take multiple parameters

echo "Welcome ", $name, "!";

Regarding using single or double quotes the difference is negligible, you can do tests with large numbers of strings to test for yourself.


I know this is an old question, but I think someone has to mention all pros & cons:

Better Syntax: That's personal preference.

Performance: No difference. As many mentioned, double-quote might be faster if using unrealistically many variables.

Better Usage: Single quote (mostly). As @Khez said, with single quote you can concatenate anything, even function calls and variable modification, like so: echo 'hi ' . trim($name) . ($i + 1);. The only thing double-quote can do that single-quote cannot do is usage of \n, \r, \t and alike.

Readability: No difference (may personal preference apply).

Writability/Re-Writability/Debugging: In 1-line statements there is no difference, but when dealing with multiple lines, it's easier to comment/uncomment lines while debugging or writing. For example:

$q = 'SELECT ' .
     't1.col1 ' .
     ',t2.col2 ' .
   //',t3.col3 ' .
     'FROM tbl1 AS t1 ' .
     'LEFT JOIN tbl2 AS t2 ON t2.col2 = t1.col1 ' .
   //'LEFT JOIN tbl3 AS t3 ON t3.col3 = t2.col2 ' .
     'WHERE t1.col1 = ' . $x . ' ' .
     '  AND t2.col2 = ' . $y . ' ' .
   //'  AND t3.col3 = ' . $z . ' ' .
     'ORDER BY t1.col1 ASC ' .
     'LIMIT 10';

Less Escaping: Single-quote. For single quote you need to escape 2 characters only (' and \). For double quote you need to escape 2 characters (", \) and 3 more if required ($, { and }).

Less Changes: Single quote. For example if you have the following code:

echo 'Number ' . $i . '!';

And you need to increment 1 to $i, so it becomes likes:

echo 'Number ' . ($i + 1) . '!';

But for double quote, you will need to change this:

echo "Number $i!";

to this:

echo "Number " . ($i + 1) . "!";

Conclusion: Use what you prefer.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to concatenation

Pandas Merging 101 What does ${} (dollar sign and curly braces) mean in a string in Javascript? Concatenate two NumPy arrays vertically Import multiple csv files into pandas and concatenate into one DataFrame How to concatenate columns in a Postgres SELECT? Concatenate string with field value in MySQL Most efficient way to concatenate strings in JavaScript? How to force a line break on a Javascript concatenated string? How to concatenate two IEnumerable<T> into a new IEnumerable<T>? How to concat two ArrayLists?