php - insert a variable in an echo string

Mechaflash picture Mechaflash · Nov 8, 2011 · Viewed 240.8k times · Source
$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?

Answer

Derek picture Derek · Nov 8, 2011

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;