Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are semicolons in PHP optional?

Tags:

syntax

php

I know that PHP, just like Java, and C++ use semicolons to terminate statements, so I'm wondering about using PHP inline with HTML. I am wondering why omitting semicolons works.

For example, why does the following code work?

<?php if(true): ?>
  <p>Hello World !!!</p>
<?php endif ?>

Note: there is no semicolon after endif in <?php endif ?>

like image 725
Kagiso Marvin Molekwa Avatar asked Dec 18 '22 20:12

Kagiso Marvin Molekwa


2 Answers

In general, I would always recommend including the semi-colon, but you're right, it can be dropped in this instance.

You may only drop the semi-colon after a statement when the statement is followed immediately by a closing PHP tag -- ie ?>.

This is documented in the PHP documentation here: http://php.net/manual/en/language.basic-syntax.instruction-separation.php

This is a feature from the earliest days of the language, aimed at making templated code slightly easier to read.

Unlike Javascript, there are no other circumstances where dropping the semi-colon is permitted.

like image 132
Spudley Avatar answered Jan 05 '23 10:01

Spudley


<?php if(true): ?>
  <p>Hello World !!!</p>
<?php endif ?>

reads as

<?php
if (true):
 echo "  <p>Hello World !!!</p>"
endif;
?>

which is a variation of

<?php
if (true) {
 echo "  <p>Hello World !!!</p>"
}
?>

which should only be used in a "html template" when no template engine is used while a variation below is used in standard php files

semicolon should not be used in one-line code blocks as per standard (PSR https://www.php-fig.org/psr/) which is extremely valuable to follow

*not mentioning surrounding line breaks

like image 25
Marius Gri Avatar answered Jan 05 '23 09:01

Marius Gri