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

html, php, variables

Solution

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.

Problem

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?

Original source

Related problems