Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP variable interpolation vs concatenation [duplicate]

What is the difference between the two following methods (performance, readability, etc.) and what do you prefer?

echo "Welcome {$name}s!" 

vs.

echo "Welcome " . $name . "!"; 
like image 794
Aley Avatar asked May 28 '13 11:05

Aley


People also ask

What is the difference between interpolation and concatenation?

Concatenation allows you to combine to strings together and it only works on two strings. Swift uses string interpolation to include the name of a constant or variable as a placeholder in a longer string, and to prompt Swift to replace it with the current value of that constant or variable.

What is variable interpolation in PHP?

Variable interpolation is adding variables in between when specifying a string literal. PHP will parse the interpolated variables and replace the variable with its value while processing the string literal.

Does PHP have string interpolation?

PHP String formatting String interpolationYou can also use interpolation to interpolate (insert) a variable within a string. Interpolation works in double quoted strings and the heredoc syntax only. $name = 'Joel'; // $name will be replaced with `Joel` echo "<p>Hello $name, Nice to see you.


1 Answers

Whatever works best for you works... But if you want to go for speed use this:

echo 'Welcome ', $name, '!'; 

The single quotes tell PHP that no interpretation is needed, and the comma tells PHP to just echo the string, no concatenation needed.

like image 151
Borniet Avatar answered Oct 21 '22 00:10

Borniet