Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - insert a variable in an echo string

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

like image 256
Anthony Miller Avatar asked Nov 08 '11 17:11

Anthony Miller


People also ask

How do you add variables in echo?

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.

How do I echo text and variable in PHP?

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.

How do you call a variable in a string in PHP?

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.


2 Answers

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; 
like image 102
Derek Avatar answered Sep 21 '22 15:09

Derek


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

like image 42
TURTLE Avatar answered Sep 19 '22 15:09

TURTLE