Write short echo tags in PHP
Before we go any further... did you know that we can mix & match HTML & PHP?
Let’s wrap our PHP echo inside an
<h1> tag, and also of course need our closing PHP bracket to tell PHP to stop parsing our code as PHP:
<h1><?php echo 'Hello world!'; ?></h1>
Refreshing our page, we will see that our echo is wrapped inside an h1 tag. Cool!
Since this open php bracket, echo, closing PHP bracket format is so common, PHP created a shorthand syntax for doing this called a “short echo tag”.
Rather than typing a normal opening php tag, we will use less than, question mark, and an equal sign:
<h1><?= echo 'Hello world!'; ?></h1>
When we do this, we are saying php echo. This means that we can also drop the
<h1><?= 'Hello world!'; ?></h1>
Finally, since short echo tags are always closed up right away, this tells PHP that execution is complete. Because of this, we can also remove the semicolon.
<h1><?= 'Hello world!' ?></h1>
I never use semicolons with short echo tags, because it just makes code a lot cleaner to read.
Wasn’t this update neat? If we refresh our page, we’ll see that everything still outputs the same.
So these two lines are exactly equivalent according to the PHP processor.
<h1><?= 'Hello world!' ?></h1> <h1><?php echo 'Hello world!'; ?></h1>
When you have the option to use two different pieces of code, always opt for the version that is the shortest and doesn’t sacrifice readability. Less code almost always leads to less bugs, because it makes your code easier to reason about when it comes time to debug code that isn’t working.