PHP Syntax

The PHP syntax is based on C, Java, and Perl, so if you've used any of those languages PHP will look familiar to you.

Creating a PHP file is similar to creating an HTML file. In fact, most PHP files are a mixture of PHP code and HTML.

Creating a PHP File

To create a PHP file, simply do the following:

  1. Create a new file in your favorite editor
  2. Type some PHP code
  3. Save the file with a .php extension

The .php extension tells the web server that it needs to process this as a PHP file. If you accidentally save it with a .html extension the server won't process your PHP code and the browser will just output it all to the screen.

OK, so that sounds easy. My guess is that you already know how to create a new file and save it, so let's concentrate on the other bit — the "type some PHP code" bit.

Basic Code Syntax

Scripting Blocks

Every block of PHP code must start with <?php and end with ?>. The following example outputs the text "PHP is easy!" to the screen:

Note: If your server supports it, you can leave off the php bit (so that it starts off like this <? echo...), but I'd recommend you keep it. This way, you won't run into any compatibility problems that you could have easily avoided.

Semi-Colons

You need to place a semi-colon (;) at the end of each line of PHP code. This tells the server that a particular statement has finished.

Comments

In the programming world, "comments" refer to small pieces of narrative within the code that can be useful in assisting other programmers interpret the meaning of the code. They can also be useful to yourself if you need to return to a piece of code many months (or years) after you'd written it. These comments aren't displayed to the user, instead, the server ignores them - they are purely for the programmers!

To write a comment in PHP, you prefix single line comments within two forward slashes (//) or, if the comment spans multiple lines, you need to open the whole block with a forward slash and asterisk (/*) then close it with an asterisk and forward slash (*/).

Example

White Space, Carriage Returns, etc

You can use tabbing, spaces, carriage returns etc to indent and format your code - this won't cause any issues for the PHP interpreter. As long as you don't forget to close each line with a semi-colon.

Displaying the Output

To display PHP files in a browser, you need to type the full http path. For example, something like this: http://localhost/php_syntax_example.php. In other words, you can't view the file using your file system's path (like you can with HTML files). For example, you can't just type something like this: C:\\inetpub\wwwroot\php_syntax_example.php.

Using the http path means that you are accessing the file via the web server. The web server knows that any file with a .php extension needs to be processed by PHP.