Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php variable in html no other way than: <?php echo $var; ?>

I work a lot in mixed HTML and PHP and most time I just want solid HTML with a few PHP variables in it so my code look like this:

<tr><td> <input type="hidden" name="type" value="<?php echo $var; ?>" ></td></tr> 

Which is quite ugly. Isn't there something shorter, more like the following?

<tr><td> <input type="hidden" name="type" value="$$var" ></td></tr> 

This is possible to but you get stuck with the "" (you have to replace them all with '') and the layout is gone

echo "<tr><td> <input type="hidden" name="type" value="$var" ></td></tr>" 

Is there anything better?

like image 528
matthy Avatar asked Jan 27 '10 21:01

matthy


People also ask

How do I reference a PHP variable in HTML?

php and ?> tags, it will process the information including the echo method. The variable's value will be substituted for the variable in the HTML tag. The same case can be applied to other PHP print methods, such as print and print_r.

What this $var mean in PHP?

The var keyword in PHP is used to declare a property or variable of class which is public by default. The var keyword is same as public when declaring variables or property of a class.

Is echo a variable in PHP?

The echo is used to display the output of parameters that are passed to it. It displays the outputs of one or more strings separated by commas. The print accepts one argument at a time & cannot be used as a variable function in PHP. The print outputs only the strings.


2 Answers

There's the short tag version of your code, which is now completely acceptable to use despite antiquated recommendations otherwise:

<input type="hidden" name="type" value="<?= $var ?>" > 

which (prior to PHP 5.4) requires short tags be enabled in your php configuration. It functions exactly as the code you typed; these lines are literally identical in their internal implementation:

<?= $var1, $var2 ?> <?php echo $var1, $var2 ?> 

That's about it for built-in solutions. There are plenty of 3rd party template libraries that make it easier to embed data in your output, smarty is a good place to start.

like image 98
meagar Avatar answered Sep 19 '22 18:09

meagar


Use the HEREDOC syntax. You can mix single and double quotes, variables and even function calls with unaltered / unescaped html markup.

echo <<<MYTAG   <tr><td> <input type="hidden" name="type" value="$var1" ></td></tr>   <tr><td> <input type="hidden" name="type" value="$var2" ></td></tr>   <tr><td> <input type="hidden" name="type" value="$var3" ></td></tr>   <tr><td> <input type="hidden" name="type" value="$var4" ></td></tr> MYTAG; 
like image 23
code_burgar Avatar answered Sep 20 '22 18:09

code_burgar