Home >Backend Development >PHP Tutorial >Why Doesn't My PHP Variable Render Inside a Single-Quoted Echoed String?

Why Doesn't My PHP Variable Render Inside a Single-Quoted Echoed String?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 15:36:15765browse

Why Doesn't My PHP Variable Render Inside a Single-Quoted Echoed String?

Inserting Variables into Echoed Strings in PHP

Echoing strings and inserting variables into them is a common practice in PHP. This article explores a scenario where a PHP variable is not rendered within an echoed string.

The code snippet provided attempts to insert the variable $i into an HTML element class attribute:

$i = 1;
echo '
<p class="paragraph$i">
</p>
';
++i;

However, this code fails to output the desired result due to the use of single quotes for the echoed string. Single quotes in PHP do not parse variables within them.

Solution:

To successfully insert a variable into an echo string, one can use double quotes or a dot to extend the echo. Here are the options:

  • Double Quotes:

    $variableName = 'Ralph';
    echo "Hello $variableName!";
  • Dot Extension:

    echo 'Hello '.$variableName.'!';

Applying these solutions to your specific case:

$i = 1;
echo '<p class="paragraph'.$i.'"></p>';
++i;

OR

$i = 1;
echo "<p class='paragraph$i'></p>";
++i;

The above is the detailed content of Why Doesn't My PHP Variable Render Inside a Single-Quoted Echoed String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn