PHP Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.21

PHP Syntax

PHP Tutorials - Herong's Tutorial Notes © Dr. Herong Yang

Non ASCII Characters with MySQL

Inputting Non ASCII Characters

Controlling Response Header Lines

HTTP Request Variables

Sessions

Using Cookies

PHP SOAP Extension

PHP SOAP Extension - Server

Directories, Files and Images

Using MySQL with PHP

... Table of Contents

This chapter describes:

  • How to begin and end a PHP code block.
  • How a PHP input file will be processed.
  • How to enter comments in a PHP code block.

PHP Code Blocks

Like any other scripting language, PHP is used to transform text information from an input to an output by mixing PHP code segments in the input text. Here is how a PHP input file should look like:

text PHP_code text PHP_code text PHP_code ...

There are 3 basic ways to mark the beginning and ending of a PHP code segments:

1. HTML "script" tag: <script language="php">PHP_code</script>

2. XML processing instruction: <?php PHP_code ?>

3. Short XML processing instruction: <? PHP_code ?>

PHP Processing Behavior

As I mentioned previously, a PHP input is a sequence text blocks and PHP code blocks. The PHP engine will process the sequence as if it was a single PHP code block by:

  • First converting each text block into a PHP statement of print "text".
  • Then joining code blocks with the converted print statements to form a single PHP code block.

PHP's processing behavior is very similar to Active Server Page (ASP)'s processing behavior.

Now let's see an example PHP input file:

<?php /* HeadOrTail.php
* Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
*/ ?>
I am tossing a coin now. Guess what the result will be? 
<?php $coin = rand(0,1); ?> 
<?php if ($coin==1) { ?>
   Head
<?php } else { ?>
   Tail
<?php } ?>

If you run this file, you may get:

I am tossing a coin now. Guess what the result will be?

   Tail

Of course, we could rewrite HeadOrTail.php as HeadOrTailModified.php:

<?php /* HeadOrTailModified.php
* Copyright (c) 2002 by Dr. Herong Yang
*/ ?>
I am tossing a coin now. Guess what the result will be? 
<?php $coin = rand(0,1);
if ($coin==1) { 
   print "   Head";
} else {
   print "   Tail";
} ?>

PHP Comments and Statement Delimiter

There are 3 ways to enter comments in a PHP code block:

  • Perl style: Using "#"
  • Java style: Using "//"
  • C style: Using "/*" and "*/"

PHP uses semicolon ";" as the statement delimiter.

Dr. Herong Yang, updated in 2006
PHP Tutorials - Herong's Tutorial Notes - PHP Syntax