Syntax
PHP tags
PHP code must be put between some special characters
<?php ?> <? ?> // with short_open_tag enabled or php with option --enable-short-tags <script language="php"> </script> // old style <% %> // ASP style asp_tags enabled
Other formats
<?php echo 'message'; ?> // this are equivalents <?= 'message'; ?> // if short_open_tag is enabled or PHP > 5.4 <%= 'message'; ?> // if asp_tags is enabled
PHP blocks mixed with HTML code
<?php if ($expression == true): ?> Text if true <img src="/image.jpg" /> <?php else: ?> HTML code for else <a href="/branch.html">branch</a>. <?php endif; ?>
Some exceptions
<?php echo '<?xml version="1.0" encoding="UTF-8" ?>'; ?> // xml files must start with this to be PHP compatible
<?php // not allowed as the only text in PHP 5.2 or less
Best practice
?> // don't use ending tags in php only files to prevent sending headers if you put a space after ?> <?= 'text'; ?> // not recomanded for redistributable code or changing environments
Comments
Single line comments
<?php // comment ?>
<?php # comment ?>
<?php // comment ends at the end of the line
// or at ending tag ?> here is outside comment
<script language="php"> //this comment doesn't end at script tag ending </scrip>
Multiline comments
<?php /* starts here
continues here
ends here */ ?>
Comments mistakes
<?php
//echo '<?php code ?>'; ?>
<?php /*
$pattern = "/^\d.*/";
*/
<?php
/*
echo 'Some text'; /* Can't imbricate multiline comments */
*/