Home >Backend Development >PHP Tutorial >How Do I Properly Insert PHP Variables into Echoed Strings?
PHP: Inserting Variables into Echoed Strings
When attempting to integrate variables into echoed strings in PHP, one might encounter issues.
Problem:
The code below fails to insert the variable $i into the echoed string:
$i = 1; echo ' <p class="paragraph$i"> </p> '; ++i;
Solution:
The key to resolving this issue lies in the quotes used for the echoed string. Single quotes do not parse PHP variables, so one must use double quotes or a dot (.) to extend the echo.
Using Double Quotes:
$variableName = 'Ralph'; echo 'Hello ' . $variableName . '!';
Using a Dot to Extend the Echo:
echo "Hello $variableName!";
Applying to the Given Code:
In the given code, the following fixes apply:
Option 1 (Double Quotes):
$i = 1; echo '<p class="paragraph' . $i . '"></p>'; ++i;
Option 2 (Dot to Extend Echo):
$i = 1; echo "<p class='paragraph$i'></p>"; ++i;
The above is the detailed content of How Do I Properly Insert PHP Variables into Echoed Strings?. For more information, please follow other related articles on the PHP Chinese website!