Hacking with PHP has been updated for PHP 7 - click here! >>

Opening and closing code islands

There are two main ways to open a PHP code island (to enter PHP parsing mode), and you are welcome to choose which you prefer. The most common (and recommended) manner is to use <?php to enter PHP mode, and ?> to leave PHP mode, however you can also use the short tags version, <? and ?>.

The short version has one big advantage and one big disadvantage. The advantage is that you can output information from your script by using a special short tags hack, <?=. Here is how that looks:

<?="Hello, world!"

Here is the equivalent written using the standard open and closing tags:

    print "Hello, world!";

As you can see, the short tags version is much shorter, if a little harder to read. However, the big downside to the short version is that it clashes with XML, which also uses <? to open code blocks. This means that if you try to use XML and short-tagged PHP together, you'll almost certainly encounter problems - this is the primary reason people recommend using the normal open and close tags.

You can switch into and out of PHP mode by using <?php and ?> whenever you want to and as often as you want to.


If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Comments >>

Previous chapter: Code blocks

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.