PHP Syntax

PHP Block

From the Introduction to PHP, we know that PHP is compiled on the server and then passed to the browser as HTML. To let the server know that a file contains PHP, we use the .php extension (i.e. index.php ).

In addition to PHP, .php files can also contain HTML, CSS, and JavaScript. To help the compiler know where the PHP begins and ends, we place PHP code within <?php and ?>.

...
<body><h1>This is HTML</h1>
<?php //PHP Code! ?>
<p>More HTML</p>
...

TIP

If the .php file contain only PHP, the closing PHP block ?> can be and should be omitted.

Echo Statement

PHP was designed to display content in a browser in the form of HTML. The simplest way to display the result of PHP code is to use the echo statement. The echo statement outputs a string that can be read by the browser.

...
<body><h1>This is HTML</h1>
<?php echo "Hello, World!"; ?>
<p>More HTML</p>
...

The Semicolon

Each statement in PHP MUST end with a semicolon. An omitted semicolon will cause a syntax error.

TIP

It is possible to omit the semicolon if it is the last statement in a PHP block, however, this goes against coding standards and best practices.

The code below would result in a syntax error and would prevent the page from compiling properly.

...
<body><h1>This is HTML</h1>
<?php 
   echo "Hello, World!";
   echo "I am a PHP echo statement!" // This will cause an error
   echo "Oops, I forgot my semicolon"; 
?>
<p>More HTML</p>
...

Comments

Comments are an effective way to leave notes or instructions about the code you have written. It is important to use comments regularly and effectively. We will learn about how to do that later in the course. For now, we learn how to create a comment.

PHP, like JavaScript, has two types of comments. Single line comments that start begin with two forwards slashes (//) and continue to the end of the line. Multi-line comments start with a forward slash followed by a asterisk (/*) and will continue until an asterisk is followed by a forward slash (*/).

<?php
  // This is a single line comment
  /* This is
     a multiline comment */
?>