Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active May 26, 2023 03:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/c280af1a0072b20876e89ba2fb7ea3e4 to your computer and use it in GitHub Desktop.
Save code-boxx/c280af1a0072b20876e89ba2fb7ea3e4 to your computer and use it in GitHub Desktop.
Display PHP Variable in HTML

HOW TO DISPLAY PHP VARIABLES IN HTML

https://code-boxx.com/display-php-variables-in-html/

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<?php
// (A) THE VARIABLES
$first = "foo";
$second = "bar";
?>
<!-- (B) OUTPUT VARIABLES -->
<p><?php echo $first; ?></p>
<p><?php echo $second; ?></p>
<?php
// (A) THE VARIABLES
$var = "foo";
$arr = ["Apple", "Beet", "Cherry"];
?>
<!-- (B) OUTPUT VARIABLE -->
<p><?=$var?></p>
<!-- (C) COMBINING THE USE OF DELIMITER AND SHORT TAG -->
<ul>
<?php foreach ($arr as $fruit) { ?>
<li><?=$fruit?></li>
<?php } ?>
</ul>
<?php
// (A) ECHO STRING OF HTML
$first = "foo";
$second = "bar";
echo "<p>$first $second</p>";
// (B) DUMMY ARRAY
$person = [
"name" => "Jon Doe",
"email" => "jon@doe.com"
];
// (C) THIS WILL NOT WORK!
// echo "<p>$person["name"] - $person["email"]</p>";
// (D) WRAP VARIABLES IN CURLY BRACES
echo "<p>{$person["name"]} - {$person["email"]}</p>";
<?php
// (A) DUMMY ARRAY
$person = [
"name" => "Jon Doe",
"email" => "jon@doe.com"
];
// (B) FORMATTED PRINT
foreach ($person as $k=>$v) {
printf("<div><strong>%s:</strong> %s</div>", $k, $v);
}
// (C) THE USEFUL PARTS...
$val = 123.45678;
printf("<p>ROUND OFF 2 DECIMAL PLACES %0.2f</p>", $val);
$val = 0.432;
printf("<p>PAD UP TO 5 ZEROS, 2 DECIMAL PLACES %08.2f</p>", $val);
$val = "123";
printf("<p>PAD WITH DOTS %'.10d</p>", $val);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment