php - insert a variable in an echo string

266,462

Solution 1

Single quotes will not parse PHP variables inside of them. Either use double quotes or use a dot to extend the echo.

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

OR

echo "Hello $variableName!";

And in your case:

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

OR

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

Solution 2

Always use double quotes when using a variable inside a string and backslash any other double quotes except the starting and ending ones. You could also use the brackets like below so it's easier to find your variables inside the strings and make them look cleaner.

$var = 'my variable';
echo "I love ${var}";

or

$var = 'my variable';
echo "I love {$var}";

Above would return the following: I love my variable

Solution 3

Variable interpolation does not happen in single quotes. You need to use double quotes as:

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

Solution 4

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

should do the trick.

Solution 5

echo '<p class="paragrah"' . $i . '">'
Share:
266,462
Anthony Miller
Author by

Anthony Miller

"Your competition is a hungry immigrant with a digital handheld assistant. America is made up of immigrants... if your children are to be successful they must act like immigrants in their own country. Just by being born here doesn't give you the ability to be successful... it is the work ethic... the pioneering ethic... the service ethic that will win. Your competition is always a hungry immigrant with a digital assistant: hungry in the belly for food, hungry in the mind for knowledge, and the hunger is something that should never leave you." ~Dr. Dennis Waitley

Updated on November 24, 2020

Comments

  • Anthony Miller
    Anthony Miller over 3 years
    $i = 1
    echo '
    <p class="paragraph$i">
    </p>
    '
    ++i
    

    Trying to insert a variable into an echoed string. The above code doesn't work. How do I iterate a php variable into an echo string?