Alternative Syntax & Embedding PHP in HTML

Alternative Syntax & Embedding PHP in HTML in PHP: --- A charity's mailing room sends out tens of thousands of appeal letters, and the body of every letter is…


The Analogy: The Mailing Room's Addressing Machine

A charity's mailing room sends out tens of thousands of appeal letters, and the body of every letter is identical -- the same heading, the same paragraphs, the same printed signature at the foot. That fixed text is pre-printed by the ream and stacked in a tray. What differs from letter to letter is small: the recipient's name and address, and perhaps a line thanking them for a specific past gift. The addressing machine's whole job is to carry each pre-printed sheet past a stamping head that drops those few variable details into the blank boxes left waiting for them. The letter is mostly constant, punctuated by little windows of variation.

That is exactly the shape of a PHP template. A web page is mostly fixed HTML -- the layout, the headings, the navigation -- with only a few spots where a value must be dropped in: a name, a price, a list of items. In a template you write the HTML plainly, as ordinary text, and open a small <?php ?> window only where something must vary. The short echo tag <?= ?> is the stamping head at its simplest: it presses one value into one box and lifts straight off again, exactly as the machine stamps a name into the address window and moves on.

Some letters need a repeated section -- a list of the donor's past gifts, one line each -- so the operator engages a repeat lever that cycles the stamping head down the page once per item, drawing plates from a small tray until the tray is empty. That repeat lever is a loop, and here the machine offers the operator a choice of controls. The cheap machines mark the start and end of a repeat with tiny unlabelled notches that you must squint to find among the dense text; the good machines have two broad levers stamped START REPEAT and END REPEAT. PHP offers the same choice. The ordinary brace form buries { and } in a page already thick with angle brackets, while the alternative form -- foreach (...): opened and endforeach; closed -- reads like those labelled levers, so a person scanning the page can see at a glance where the repeated section begins and ends.

The failures are instructive. If the operator forgets to throw the END REPEAT lever -- omits the endforeach; -- the head never lifts: it stamps on past the intended box, running rows down into the signature and off the foot of the page. PHP answers a missing endforeach; with a parse error, refusing to run the page at all. If a plate is missing from the tray, the machine stamps a blank where a name should be -- and PHP, handed an undefined variable, warns and prints nothing into that slot. Worst of all is misregistration: the plate drifts so the stamped name lands half in its box and half across the fixed text, colliding with the letter's own printing. That is precisely what happens when you drop an unescaped value into your HTML and its characters collide with the page's own tags -- the reason every value pressed into a template should first be run through htmlspecialchars.


Syntax or Core Structure

Any file processed by PHP is treated as plain text -- emitted verbatim -- until the parser meets an opening <?php tag; from there it runs code until the closing ?>, then drops back to emitting text. A template exploits this by staying in text mode for the HTML and opening only brief islands of code. The short echo tag <?= $value ?> is shorthand for <?php echo $value; ?> and has been available unconditionally since PHP 5.4. The alternative syntax replaces each block's braces with a colon and a matching endforeach;, endif;, endfor;, endwhile;, or endswitch;.

<?php $items = ['Bolts', 'Nuts & Washers', 'Seals']; ?>
<ul>
<?php foreach ($items as $item): ?>
    <li><?= htmlspecialchars($item) ?></li>
<?php endforeach; ?>
</ul>

The HTML text is written directly; only the loop and the value output sit inside PHP tags. Note the second item: its ampersand is turned into &amp; by htmlspecialchars, so the value cannot collide with the page's own markup. Note too that the newline immediately after each ?> is swallowed by PHP -- that is why the output has no blank lines where the foreach and endforeach; tags stood.

Output:

<ul>
    <li>Bolts</li>
    <li>Nuts &amp; Washers</li>
    <li>Seals</li>
</ul>

The rendered list carries only the four spaces of indentation from the template's <li> line; the control-flow tags leave no trace of their own in the output, which is what makes a well-written template read almost like static HTML.


Technical Depth: The Rules That Make Templates Behave

Every block has an alternative form

The alternative syntax is not a special templating language; it is a second spelling of the ordinary control structures, and the two forms are interchangeable. In a file dense with HTML the colon-and-end form wins because each block announces plainly where it closes, rather than leaving you to match a } against the correct { several screens away.

StructureBrace formAlternative form
Conditionalif (x) { }if (x): ... endif;
Foreach loopforeach (a as v) { }foreach (a as v): ... endforeach;
For loopfor (init; test; step) { }for (...): ... endfor;
While loopwhile (x) { }while (x): ... endwhile;
Multi-way branchswitch (x) { }switch (x): ... endswitch;

One rule catches beginners: you cannot mix the forms within a single block. If you open with if (x): you must close with endif;, never }, and the reverse holds too. The elseif and else keywords work in both forms, but under the alternative syntax each is followed by a colon, as in elseif ($n > 0): and else:.

The swallowed newline after ?>

PHP removes exactly one newline immediately following a closing ?> tag. This is deliberate: it keeps a control-flow tag sitting on its own line from injecting a blank line into the output. The rule removes only a single newline, and only the one directly after ?> -- leading spaces on the next line survive, which is why template indentation is preserved. The example below combines an inline if: inside a foreach: to mark done items, all on one physical line so no stray newlines appear:

<?php
$tasks = [
    ['label' => 'Draft', 'done' => true],
    ['label' => 'Review', 'done' => false],
    ['label' => 'Publish', 'done' => false],
];
?>
<ol>
<?php foreach ($tasks as $t): ?>
    <li><?php if ($t['done']): ?>[x]<?php else: ?>[ ]<?php endif; ?> <?= htmlspecialchars($t['label']) ?></li>
<?php endforeach; ?>
</ol>

Because the whole if: else: endif; sits within the <li> line, no tag stands alone and nothing is left to swallow inside the list item; each item renders on exactly one line. The single space between endif; ?> and the label is literal text in the template and is preserved -- swallowing touches newlines only, never spaces.

Output:

<ol>
    <li>[x] Draft</li>
    <li>[ ] Review</li>
    <li>[ ] Publish</li>
</ol>

Real World Example: Rendering a Navigation Bar

Almost every page on a site shares one navigation bar, and exactly one item in it should be marked as the current page. Rather than hand-writing the markup on every page with the active item hard-coded, you drive the bar from a list of pages and a single $current slug, and let a template decide which item gets the active treatment. This is templating at its most typical: fixed structure, a repeated row, and one conditional inside the loop.

<?php
$pages = [
    ['slug' => 'home',      'label' => 'Home'],
    ['slug' => 'catalogue', 'label' => 'Catalogue'],
    ['slug' => 'about',     'label' => 'About Us'],
    ['slug' => 'contact',   'label' => 'Contact'],
];
$current = 'catalogue';
?>
<nav>
<ul>
<?php foreach ($pages as $page): ?>
<?php if ($page['slug'] === $current): ?>
    <li class="active"><?= htmlspecialchars($page['label']) ?></li>
<?php else: ?>
    <li><a href="/<?= $page['slug'] ?>"><?= htmlspecialchars($page['label']) ?></a></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
</nav>

The foreach: walks the page list, and for each page the if: else: endif; chooses between two <li> shapes: the current page becomes plain text with an active class, every other page becomes a clickable link. Each control-flow tag sits on its own line, and because PHP swallows the newline after every ?>, none of them leaves a blank line behind. The output is clean, indented HTML that a browser -- and a human reading the page source -- can follow directly.

Output:

<nav>
<ul>
    <li><a href="/home">Home</a></li>
    <li class="active">Catalogue</li>
    <li><a href="/about">About Us</a></li>
    <li><a href="/contact">Contact</a></li>
</ul>
</nav>

The strength of this approach is that the navigation lives in one place: to add a page you add one row to $pages, and every page that includes this template gains the link with the correct item highlighted. Using === for the $current comparison, rather than the loose match a switch would use, means a slug is matched by exact string and nothing surprising slips through. Wrapping each label in htmlspecialchars means a label containing an ampersand or angle bracket is rendered as text rather than breaking the surrounding tags.

The template carries a genuine security flaw, though, and it is worth naming exactly. The label is escaped with htmlspecialchars, but the slug dropped into the href is not: href="/<?= $page['slug'] ?>" writes the raw slug straight into an attribute. Every slug here is a safe word, so the output looks fine, but the moment a slug can come from anywhere less trusted -- a database row an editor filled in, a category name derived from user input -- a value containing a double quote would close the attribute early and let an attacker inject further attributes or a javascript: handler. The fix is to escape the slug for its context too: htmlspecialchars at minimum, or rawurlencode since it is a URL path segment. The inconsistency is the real danger, because escaping the label but not the slug looks careful while leaving a hole open, and code that is half-escaped invites the reader to assume the whole page is safe.


Common Mistakes

  1. Dropping a value into HTML without escaping it. Writing <?= $userName ?> straight into a page lets any <, >, &, or quote in the value collide with your markup, which is the classic cross-site scripting hole. Run every dynamic value through htmlspecialchars on output, and escape for the specific context -- an attribute needs escaping just as much as element text does.
  1. Mixing brace and alternative forms in one block. Opening with if ($x): and trying to close with }, or opening with { and closing with endif;, is a parse error. Each block must be closed in the same style it was opened; pick one form per structure and stay with it.
  1. Forgetting the semicolon on the closing keyword. The alternative closers are endif;, endforeach;, endwhile;, endfor;, and endswitch; -- each ends in a semicolon. Omitting it, or misspelling endforeach as endeach, produces a parse error that names a line far from the real mistake.
  1. Relying on the short tag <? ?>. The bare short-open tag depends on the short_open_tag setting and may be disabled on the server, so a page that works locally can render raw PHP source in production. The short echo tag <?= ?> is always available and is the only short form you should use.
  1. Leaving a newline or space after the final ?>. In a file that ends with a ?> followed by a blank line, that whitespace is sent as output, which triggers the dreaded "headers already sent" error the next time code tries to set a header or start a session. In pure-PHP files, omit the closing ?> entirely.
  1. Being surprised by the swallowed newline. PHP removes one newline after each ?>. Authors who do not know this sometimes add a second blank line to compensate, then get inconsistent spacing. Learn the rule instead of fighting it: one control-flow tag per line renders cleanly precisely because of the swallow.
  1. Putting real logic inside the template. Running database queries, sorting, or heavy computation between the HTML tags mixes concerns and makes the page impossible to test or reuse. Prepare all data before the template runs, and let the template do nothing but present it.
  1. Echoing large blocks of HTML as strings. Building pages with echo "<div>...</div>"; buries the markup in quotes and escaping. Drop out of PHP with ?>, write the HTML as plain text, and reopen <?php only where a value or a loop is needed.
  1. Mismatching nested end keywords. With a foreach: wrapping an if:, the inner block must close with endif; and the outer with endforeach;. Reversing them, or closing the inner block with the outer's keyword, silently changes the structure or throws a parse error; indent nested blocks so the pairing stays visible.

Best Practices

  • Use the alternative syntax (if:, foreach:, and their end keywords) in any file that is mostly HTML, so each block announces where it closes amid the markup.
  • Escape every dynamic value at the point of output with htmlspecialchars, choosing the escaping that fits the context -- element text, an attribute, or a URL path segment each have their own correct treatment.
  • Use <?= $value ?> for output and never the config-dependent <? ?> short tag; the short echo tag is guaranteed present on every modern PHP install.
  • Keep templates free of business logic: fetch, sort, and compute everything beforehand, and let the template read like a form to be filled rather than a program to be run.
  • Omit the closing ?> in files that contain only PHP, which removes any chance of stray trailing whitespace being sent as output.
  • Drop to plain HTML rather than echoing markup as strings; reopen a PHP island only where a value must be inserted or a section repeated.
  • Keep one control-flow tag per line so PHP's newline-swallowing rule leaves your rendered HTML cleanly free of blank lines.
  • Once the native mechanics are second nature, consider a dedicated template engine such as Twig or Blade for larger projects; it automates escaping and enforces the separation of logic from presentation.

Practice Exercises

  1. Take a loop that renders an HTML table of products using the brace form and echo for each cell, and rewrite it with the alternative foreach: syntax and the <?= ?> short echo tag. Render it with a fixed array and confirm the output HTML is byte-for-byte identical to the original.
  1. Fix the navigation template's escaping flaw: change the href so the slug is escaped for its context, then add a page whose slug contains a double quote and verify that the rendered attribute is no longer broken. Explain why escaping the label alone was not enough.
  1. Write a template that renders a definition list (<dl>) from an associative array of term-to-definition pairs, using foreach ($terms as $term => $definition): and escaping both the term and the definition. Include one value containing an ampersand and confirm it renders as &amp;.
  1. Demonstrate the swallowed-newline rule for yourself: render the same small list twice, once with the foreach and endforeach; tags on their own lines and once with them inline, and compare the two rendered outputs character by character to see exactly which newlines survive.