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
Release: 2024-11-30 15:36:15
Original
754 people have browsed it

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;
Copy after login

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!";
    Copy after login
  • Dot Extension:

    echo 'Hello '.$variableName.'!';
    Copy after login

Applying these solutions to your specific case:

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

OR

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template