Home >Backend Development >PHP Tutorial >How to Properly Insert PHP Variables into Echoed HTML Strings?
Insert Variables into Echoed Strings in PHP
When trying to embed variables within echoed strings in PHP, issues can arise. Consider the following unsuccessful attempt:
<?php $i = 1; echo ' <p class="paragraph$i"> </p> '; ++i; ?>
In this case, the variable $i is not parsed within the single-quoted string. To resolve this, there are two main approaches:
$i = 1; echo " <p class=\"paragraph$i\"> </p> "; ++i;
$i = 1; echo '<p class="paragraph'.$i.'"></p>'; ++i;
Both approaches will allow PHP to parse the variable $i within the echoed string.
Therefore, the correct way to echo the HTML element with a dynamic class is:
$i = 1; echo '<p class="paragraph' . $i . '"></p>'; ++i;
The above is the detailed content of How to Properly Insert PHP Variables into Echoed HTML Strings?. For more information, please follow other related articles on the PHP Chinese website!