$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?

share|improve this question

6 Answers

up vote 11 down vote accepted

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;
share|improve this answer
I suppose only the first would work for my instance as the variable is not separated from the word. – Mechaflash Nov 8 '11 at 18:03
1  
No, it shouldn't matter, as the second one isn't outputting any space between "paragraph" and the output of the variable. – Doctor Trout Nov 8 '11 at 18:05
The 3rd won is what works for me. But I do understand the difference between double and single quotes. Just that I'm editing an open source program to make some minor customizations and I don't want to change the formatting around too much. – Mechaflash Nov 8 '11 at 18:19

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

$i = 1
echo "<p class=\"paragraph$i\"></p>";
++i;
share|improve this answer
echo '<p class="paragraph'.$i.'"></p>'

should do the trick.

share|improve this answer
echo '<p class="paragrah"' . $i . '">'
share|improve this answer
echo '<p class="paragraph'.$i.'"></p>';
share|improve this answer

Use double quotes:

$i = 1;
echo "
<p class=\"paragraph$i\">
</p>
";
++i;
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.