Should I use curly brackets or concatenate variables within strings?

All of the following does the same if you look at the output.

  1. $greeting = "Welcome, " . $name . "!";
  2. $greeting = 'Welcome, ' . $name . '!';
  3. $greeting = "Welcome, $name!";
  4. $greeting = "Welcome, {$name}!";

You should not be using option 1, use option 2 instead. Both option 3 and 4 are the same. For a simple variable, braces are optional. But if you are using array elements, you must use braces; e.g.: $greeting = "Welcome, {$user['name']}!";. Therefore as a standard, braces are used if variable interpolation is used, instead of concatenation.

But if characters such as tab (\t), new-line (\n) are used, they must be within double quotations.

Generally variable interpolation is slow, but concatenation may also be slower if you have too many variables to concatenate. Therefore decide depending on how many variables among other characters.

Leave a Comment