PHP Syntax

Just as each language has its own proper sentence structure and rules it must follow, PHP is a language which has its own rules in order for it to work correctly.

PHP Tags

All PHP code must reside within the following PHP tags:

If your code is not within these tags, it will not function.

Switching PHP On And Off

Most PHP pages will require the use of HTML to output a particular result to the end user. In this case, the execution of the PHP code can be switched on and off, thus allowing you to insert HTML:

What is your name?

This bit of code would display:

What is your name?
My name is John.

Notice how we were able to alternate between HTML and PHP.

Saving PHP Pages

Just as HTML pages must be saved with an .html or .htm extension, pages which contain PHP code must be saved with a .php file extension. Even PHP pages which contain HTML within them must be saved with a .php file extension.

PHP Line Breaks

The end of each line in PHP must end with a semicolon (;). You will notice this in all the code examples shown on this site.

Leaving PHP Comments

You may already be familiar with how to leave comments in HTML:

You can also leave single and multi line comments using PHP.

For more information, see PHP comments.

Using Single Quotes With Strings

Whenever using a single quote anywhere within a string, you must escape it using a backslash (\). For example:

$thestring = “ It\’s my favorite website!”;

Because the word “it’s” has an apostrophe (single quote), it must be escaped with a single backslash.

Carriaged Returns

A carriaged return is made using a backslash followed by the letter “n” (\n).

For example, carriaged returns are used when defining the contents of a variable. See PHP File Write for an example.