Home >Backend Development >PHP Tutorial >How to Append Strings with PHP Variables in Concatenation and Template Literals?
Printing Strings with PHP Variables
In PHP, you can include variables within strings using the concatenation operator ('.'). However, sometimes you may need to include characters that conflict with PHP syntax, such as quotes or whitespace.
Question:
How can I print a string with the variable $widthpx appended with "px"?
Solution:
There are two methods to achieve this:
<code class="php">$bla = '<div class="vote_pct" style="width: '.$width.'px;">';</code>
This method concatenates the string with the variable, effectively "pasting" the variable's value into the string.
Template literals, introduced in PHP 5.6, use curly braces ({ }) to encapsulate expressions that are evaluated at runtime and interpolated into the string. This method supports multi-line strings and allows for easier expression evaluation.
<code class="php">$bla = "<div class=\"vote_pct\" style=\"width: ${width}px;\">";</code>
This method leverages template literals to dynamically include the variable's value. Template literals are also known as "heredoc" and "nowdoc" syntax.
The above is the detailed content of How to Append Strings with PHP Variables in Concatenation and Template Literals?. For more information, please follow other related articles on the PHP Chinese website!