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 ?>
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.
<?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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With