PHP in HTML

Embedding PHP in HTML and the Alternative Syntax

A .php file is HTML until PHP meets <?php; everything up to the next ?> is code, and whatever it echoes replaces it. <?= $x ?> is shorthand for <?php echo $x ?> and is always available. Inside markup, the alternative syntax for control structures reads better than braces split across tags: if (...):, elseif (...):, else: and endif, with foreach/endforeach, for/endfor, while/endwhile and switch/endswitch to match.

catalog.php: a template using the short echo tag and the alternative syntaxPHP
<?php
$books = [
    ['title' => 'Modern PHP in Practice',    'price' => 39.90, 'stock' => 25],
    ['title' => 'Indexing Deep Dive',        'price' => 29.00, 'stock' => 0],
    ['title' => 'The Linux Server Handbook', 'price' => 42.00, 'stock' => 9],
];
?>
<ul>
<?php foreach ($books as $b): ?>
  <li><?= htmlspecialchars($b['title']) ?>, $<?= number_format($b['price'], 2) ?>
<?php if ($b['stock'] === 0): ?>
    <strong>sold out</strong>
<?php elseif ($b['stock'] < 10): ?>
    <em>only <?= $b['stock'] ?> left</em>
<?php endif ?>
  </li>
<?php endforeach ?>
</ul>
Output
<ul>
  <li>Modern PHP in Practice, $39.90  </li>
  <li>Indexing Deep Dive, $29.00    <strong>sold out</strong>
  </li>
  <li>The Linux Server Handbook, $42.00    <em>only 9 left</em>
  </li>
</ul>

PHP swallows one newline directly after ?>, so lines holding only a tag vanish, and the price line runs into </li>. Harmless in HTML, but it explains a classic bug: in a pure-PHP file, a blank line after the final ?> is sent to the browser and a later header() fails with "headers already sent". Omit the closing ?> in files that contain only PHP.

Escape every value printed into HTML with htmlspecialchars() (HTML-Safe Output and Escaping). Avoid the old short open tag <?, which depends on short_open_tag. Keep templates this thin: data above the markup, loops and output below. Laravel 2,157 's Blade (Laravel) compiles to exactly this kind of PHP.