$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?
Either use double quotes or use a dot to extend the echo. I suppose only the first would work for my instance as the variable is not separated from the word. No, it shouldn't matter, as the second one isn't outputting any space between "paragraph" and the output of the variable.
Definition and UsageThe echo() function outputs one or more strings. Note: The echo() function is not actually a function, so you are not required to use parentheses with it. However, if you want to pass more than one parameter to echo(), using parentheses will generate a parse error.
In PHP, variables can be parsed within strings specified with double quotes ( " ). This means that within the string, the computer will replace an occurence of a variable with that variable's value.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With