PHP Syntax

This video was created by Dani Krossing

The .php Extension

Just like how HTML files end with .html and CSS files end with .css, when working with PHP, the specific .php extension must be used. This extension with what informs the web server that a file may contain PHP.

The PHP Tag

To inform the PHP server which lines of code should be interpreted as PHP, we need to use the PHP tag <?php ?>. The PHP tag must be used for any and all PHP code.

NOTE

All whitespace inside of a PHP tag will be ignored by the PHP Server.

<?php phpinfo(); ?>

A single PHP file may contain multiple PHP tags and is in fact how PHP is embedded into HTML.

<?php $title = "A Simple PHP File"; ?>
<html>
  <head>
    <title><?php echo $title; ?></title>
  </head>
  <body>
    <?php echo "Hello World" ?>
  </body>
</html> 

The Semicolon

In PHP, all lines of code MUST end with a semicolon (;).

<?php
  // Semicolons at the end of each line
  $greeting = "Hello, World.";
  echo $greeting;
?>

Forgetting the semicolon will result in a syntax error.

<?php
  // This will result in a syntax error
  $greeting = "I have no semicolon."
  echo $greeting
?>

The echo Statement

The echo Statement is used to output one or more strings. It is considered to be the primary way to output data from PHP to the browser as HTML.

<?php echo "Hello, World"; ?>

To output, more than one string using echo, a comma (,) or a period (.) can be used between strings.

<?php 
  $name = "John";

  echo "Total: ", 3 + 5; // Total: 8
  echo "\n"; // creates a new line
  echo "Hello " . $name; // Hello John

NOTE

If a file only contains PHP, the closing PHP tag is NOT required.

Comments

Comments are messages that a developer leaves in the code to help explain the code or to leave a note about the code, but are completely ignored by the interpreter. Comments are a vital tool for any developer, and the better comments are used the better a developer will become.

PHP Comments can be divided into two categories: single-line comments and multi-line comments.

Single Line Comments

Single line comments start with a // and continues to the end of the line. Any text between the // and the end line will be ignored by PHP. PHP comments only work inside of PHP tags <?php ?>. Any comments outside of the PHP tag will be rendered as text by the browser.

NOTE

It is also possible to use # for single-line comments, but this is not commonly used.

<?php
  // This a single line comment
  echo "Hello, World";
?>

// This will appear as text in the browser

Multi-line Comments

Multi-line comments start with a /* and will continue until a */ is encountered.

<?php 
  /* This is a 
    multiline comment */ 
    echo "Hello, World";
?>