Php variable in html there is no other way: <? php echo $ var;?>
I work a lot in mixed HTML and PHP, and in most cases I just need solid HTML with several PHP variables, so my code looks like this:
<tr><td> <input type="hidden" name="type" value="<?php echo $var; ?>" ></td></tr> This is pretty ugly. Isnβt anything shorter, more like the following?
<tr><td> <input type="hidden" name="type" value="$$var" ></td></tr> It is possible, but you are stuck with "" (you must 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?
There is a short version of your code, which is now completely acceptable for use, despite obsolete recommendations otherwise:
<input type="hidden" name="type" value="<?= $var ?>" > which (before PHP 5.4) requires that short tags be included in your php configuration. It works exactly like the code you entered; these lines are literally identical in their internal implementation:
<?= $var1, $var2 ?> <?php echo $var1, $var2 ?> This is about embedded solutions. There are many third-party template libraries that make it easy to embed data in your output, smarty is a good place to start.
Use the HEREDOC syntax. You can mix single and double quotes, variables, and even function calls with unchanged / unshielded 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; I really think you should accept the Smarty template engine as the standard php lib for your projects.
Name: {$name|capitalize}<br> There are many template systems that offer a more compact syntax for your views. Smarty is respectable and popular. This article lists 10 others.
I would advise against using shorttags, see Are PHP Short Short Words Acceptable for Use? for more information on why.
Personally, I don't mind mixing HTML and PHP like that
<a href="<?php echo $link;?>">link description</a> As long as I have a code editor with good syntax highlighting, I think it's pretty readable. If you start echoing HTML with PHP, you will lose all syntax benefits by highlighting your HTML. Another disadvantage of HTML echo is quoted material, the next much less readable IMHO.
echo '<a href="'.$link.'">link description</a>'; The biggest advantage for me with a simple echo and a simple loop in PHP and the rest in HTML is that the indentation is consistent, which ultimately improves readability / validation.
In the php section before the HTML section, use sprinf () to create a constant string from variables:
$mystuff = sprinf("My name is %s and my mother name is %s","Suzy","Caroline"); Then, in the HTML section, you can do whatever you want, for example:
<p>$mystuff</p>