php variable in html no other way than: <?php echo $var; ?>
Yes, that is one way to output the value of a PHP variable in HTML. Here are a few other options:
Using short tags: If you have short tags enabled in your PHP configuration, you can use
<?= $var ?>
to output the value of a variable.Using a HEREDOC string: You can use a HEREDOC string to output multiple lines of HTML and include the value of a PHP variable within the HTML. For example:
<?php
$var = "Hello World!";
$html = <<<EOT
<div>
The value of the variable is: $var
</div>
EOT;
echo $html;
Watch a video course
Learn object oriented PHP
- Using a double-quoted string: You can also use a double-quoted string to output HTML and include the value of a PHP variable within the HTML. For example:
<?php
$var = "Hello World!";
echo "<div>The value of the variable is: $var</div>";
Keep in mind that you should use single quotes (') around HTML attributes to avoid having to escape double quotes. For example:
<?php
$var = "Hello World!";
echo "<div class='container'>The value of the variable is: $var</div>";