End tags in PHP

Published on Sat Jan 11 2020

I’m getting back into PHP.

This is a good thing (but more on that later!).

It has been years since I’ve been programming PHP and therefore this might seem as old news to everybody else that is doing just a little PHP programming every now and then:

You don’t have to close your PHP start tag!

Normally I’d have a file like this:

echo 'Hello world!';

… and this works perfectly well.

The problem is that the closing tag doesn’t have to end the file. There can be all sorts of crap after it (and even before the start tag, or multiple start+end tags in a file/page) – actually this is a feature and is sometimes desired:

<h1>Title of my page</h1>
<p>Welcome visitor number <?php echo visitor_count(); ?></p>
<p>Nice to have you visiting from <?php echo $_SERVER['REMOTE_ADDR']; ?></p>

This is obviously a trivial example but it shows why you’d want this.

Most of the stuff I make in PHP is not templating like this – it is actually backend APIs eg. – and adding extra content and/or whitespace would be somewhat fatal.

Therefore there is a simple little trick you can use: Don’t use the close tags if you don’t need them!

In file1.php:

echo "Hello from file1\n";

And file2.php:

echo "Hello from file2\n";

Simple. Neat. Effective.