Closing tags, semicolons & line breaks in PHP

Note that PhpStorm has a soft warning that complains about this closing bracket as a “redundant closing tag”. This is because our PHP script contains only PHP code, and it’s best to remove the closing PHP tag in this situation. We’ll do this because any whitespace or newlines added after the PHP closing tag can cause unwanted side effects and errors in specific situations.

<?php
echo('Hello world!')

Once we remove the closing bracket though, we’ll see that PhpStorm gives us a hard-warning, denoted with the red squiggly. This is an error that will cause our script to fail.

We can confirm this by refreshing our page.

This is because when we use a closing bracket, it implies that our PHP script ends. But when we take this closing tag away, we need something to tell PHP that we are done writing PHP code.

Semicolons are used to tell PHP that this current line of code is complete. So all we need to do is add a semicolon to the end of this line. Now when we refresh the page, our code successfully executes.

<?php
echo('Hello world!');

This error may seem a bit silly, but semicolons play an important role in something called “instruction separation”, which is just a fancy way of us needing to tell PHP where one line of code ends and another one begins.

For example, if we needed another line of code here:

<?php
echo('Hello world!');
echo('Hello world!!!!');

When PHP compiles and executes this code, it strips out all of the whitespace and line breaks. This means that it the final code looks something like this to the compiler:

<?php echo('Hello world!');echo('Hello world!!!!');

If we didn’t have the semicolons, PHP would be unable to determine where one line of code ends and the other starts.

<?php echo('Hello world!')echo('Hello world!!!!')

So these semicolons are sort of a delimiter for the compiler.

<?php
echo('Hello world!');echo('Hello world!!!!');


Complete and Continue  
Extra lesson content locked
Enroll to access source code, comments & track progress.
Enroll for Free to Unlock