Introduction to PHP

PHP is a server-side XHTML-embedded scripting language was created by Rasmus Lerdorf in the 1990s. "PHP" used to be an acronym for "Personal Home Page"; now it's understood to mean "PHP: Hypertext Preprocessor". When the server is requested an XHTML page with embedded PHP code, it calls the PHP interpreter, processes the document, and sends the output of processing the script in an XHTML page.

The PHP interpreter takes as input a file containing a mix of XHTML, CSS, JavaScript, and PHP code, and produce an output file containing only XHTML, CSS, and JavaScript. Any PHP code it finds in the input file is interpreted/evaluated and embedded into the original XHTML, CSS, and JavaScript. The output file is sent to the browser, and the original file is left unchanged.

PHP code is embedded in an XHTML document between <?php and ?> tags. The file must have a .php extension instead of an .html extension.

Here is an example of HTML code with embedded PHP code:

<html>
  <head>
    <title> Hello World </title>
  </head>
  <body>
    <?php print "Hello World!"; ?>
  </body>
</html>

Comments

There are three ways you can add comments in PHP code:

   // Here is a single-line comment. 
# Here is another single-line comment.
/* This is a multi-
line comment. */

Variable Names

All variable names in PHP begin with the dollar sign ($) followed by any number of letters, digits, underscores, or dollar signs. Variable names in PHP are case sensitive.

Reserved Words

and break case class
continue default do else
elseif extends false for
foreach function global if
include list new not
or require return static
switch this true var
virtual xor while  

Types

PHP uses dynamic typing; that is, variables do not have any intrinsic type, nor is the type declared. The type of a variable is simply the type of the value it is assigned.

PHP recognizes four scalar types: Boolean, integer, double, and string. There are two compound types (array and object) and two special types (resource and NULL). An unassigned variable has the special value NULL associated with it. To test if a variable has been assigned a value, you can use the function isset(). The function isset( $x ) will return true if the variable $x has been assigned a value, or false otherwise.

Boolean: can be either TRUE or FALSE. The values are case insensitive.

Integer: can be specified in decimal, octal (precede number with a 0), hexadecimal (precede the number with 0x). The size of an integer is platform dependent and can be determined using the constant PHP_INT_SIZE and the maximum value by using the constant PHP_INT_MAX.

Floating Point Numbers: are platform dependent, but usually follow 64 bit IEEE format. The floating point numbers can be expressed as:

$a = 1.234;
$b = 1.2e3;
$c = 2E-10;

Strings: A string is a series of characters. A string could have any length; the only limit is the available memory of the computer.

One way to express a string is to enclose the sequence of characters within single quotes ('). Variables and escape sequences for special characters will not be interpreted when they are embedded in single quotes.

A second way to express a string is to enclose the characters within double quotes ("). Variables and escape sequences will be interpreted when a string is enclosed in double quotes.

To include literal single or double quotes within the string, escape them with a backslash (\).

A third way of expressing strings is the heredoc format. Heredocs are multi-line strings; they're useful for specifying multiple lines to be generated into the output file.

To start a heredoc, you type the heredoc operator "<<<", an identifier, and then a newline. Beginning on the next line, you can type a multi-line string. To end the heredoc, type the same identifier alone on a line.

Heredoc text behaves just like a double quoted string without the double quotes. Variables are expanded and escape sequences used without the quotes.

   $str = <<<EOS
   This is a string 
   spanning 2 lines.
   EOS;

Here is a list of string functions. PHP has also Perl compatible regular expressions.

Arrays

In PHP an array is an ordered map of key-value pairs. An array can be used as an ordinary array, a list, hash table, and other data structures. An array is created using the array() language construct. It takes as parameters any number of comma-separated key => value pairs. A key may be either an integer or a string. Floats used as keys are truncated to integers. The value can be any PHP type.

   $arr = array(10 => false, "foo" => "bar");

An array can contain other arrays as elements, so you can make multidimensional arrays this way.

   $arr = array("arr" => array (6 => 5, 13 => 9, "a" => 42));

Using TRUE as key will evaluate to the integer 1 as a key. Using FALSE as key will evaluate to integer 0 as a key. Using NULL as a key will evaluate to the empty string (""). Arrays and objects cannot be used as keys.

To modify an existing array, assign a value by specifying the key in square brackets. This will overwrite the old value associated with the key, or create a new key-value pair if the key was not previously associated with a value.

   $arr[6] = 1000;      // change the existing value in the above array from 5 to 1000
   $arr["hello"] = 25;  // add a new key-value pair "hello" => 25

Automatic key generation: if a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1.

   // This array ...
   $arr = array (5 => 43, 32, 56, "b" => 12);

   // ... is the same as this array
   $arr = array (5 => 43; 6 => 32, 7 => 56, "b" => 12);

Some more examples:

   $arr = array (5 => 1, 12 => 2);

   $arr[] = 56;      // Same as $arr[13] = 56;

   $arr["x"] = 42;   // New element added

   // To remove a key/value pair, call the unset() function
   unset ($arr[5]);  // Removes this element 
   unset ($arr);     // Removes the array

Syntax for looping through an array:

   $arr = array (1, 2, 3, 4, 5);

   foreach ($arr as $i => $value)
   {
     unset($arr[$i]);
   }

   // Note that the key to this assignment is 5 and not 0
   $arr[] = 6;

This link takes you to a list of Array Functions.

Always use quotes around a string literal array index, but do not quote keys that are constants or variables, as this will prevent PHP from interpreting them.

   $foo[bar] = 'baz';  // bad
   $foo['bar'] = 'baz';  // good

   for ($i = 0; $i < 10; $i++)
   {
     echo "$arr['$i']";  // bad
     echo "$arr[$i]";  // good
   }

Operators

Arithmetic operators: PHP has the basic arithmetic operators: +, -, *, /, %. The division operator returns a float value unless both operands are integers and the numbers are evenly divisible. Operands of the modulus operator are converted to integers (by stripping the decimal part) before processing.

Increment / Decrement operators: PHP has the C-style increment (++) and decrement (--) operators that can be used in pre and post fix position.

Assignment operator: The value of an assignment expression is the value assigned. This is similar to a concept in C. For example,

   $a = ($b = 4) + 5;
   // $b = 4 and $a = 9

There are also the shortcut assignment operators +=, -=, *=, /=, %=, and .=. The last operator denotes string concatenation.

Bitwise operators: These operators allow you to turn specific bits within an integer on or off. The bitwise operators are: & (and), | (or), ^ (xor), ~ (not), << (shift left), and (>>) (shift right).

Relational operators: These operators allow you to compare two values. If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers.

Example Name Result
$a == $b Equal TRUE if $a is equal to $b
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type
$a != $b Not equal TRUE if $a is not equal to $b
$a <> $b Not equal TRUE if $a is not equal to $b
$a !== $b Not identical TRUE if $a is not equal to $b or they are not of the same type
$a < $b Less than TRUE if $a is less than $b
$a > $b Greater than TRUE if $a is greater than $b
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b

Logical operators:

Example Result
$a and $b and TRUE if both $a and $b are TRUE
$a or $b or TRUE if either $a or $b is TRUE
$a xor $b xor TRUE if either $a or $b is TRUE, but not both
! $a ! (not) TRUE if $a is FALSE
$a && $b & (and) TRUE if both $a and $b are TRUE
$a || $b || (or) TRUE if either $a or $b is TRUE

and, xor, or have lower precedence than the assignment operator (=). !, &&, || have higher precedence than the assignment operator.

Execution operators: PHP has one execution operator: backticks (``). These are not single quotes! PHP will attempt to execute the contents of the backticks as a shell command and the output can be assigned to a variable like so:

   $output = `ls -l`;

Error control operator: The at sign (@) when prepended to an expression in PHP will ignore any error messages generated. The error message will be saved in the variable $php_errormsg.

   $my_file = @file ('some_file') or die ("Failed opening file: $php_errormsg");

String operators: There are two string operators. The concatenation operator ('.') and the concatenating assignment operator ('.=').

   // prints "hello there"
   echo "hello" . " there"

Array operators:

Example Name Result
$a + $b Union Union of $a and $b
$a == $b Equality TRUE if $a and $b have the same key / value pairs.
$a === $b Identity TRUE if $a and $b have the same key / value pairs in the same order and of the same types.
$a != $b Inequality TRUE if $a is not equal to $b
$a <> $b Inequality TRUE if $a is not equal to $b
$a !== $b Non-identity TRUE if $a is not identical to $b
The + operator appends elements of remaining keys from the right handed array to the left handed array, whereas duplicated key are NOT overwritten.

Type operators: The instanceof operator is used to determine whether a PHP variable is an instantiated object of a certain class.

Conditionals

There are several versions of the conditional:

   if (expr)
      statement

If (expr) is TRUE then statement gets executed.

   if (expr)
      statement1
   else
      statement2

If (expr)is TRUE then statement1 gets executed. If it is FALSE then statement2 gets executed. There is also an "elseif" keyword:

   if (expr1)
      statement1
   elseif (expr2)
      statement 2
   else
      statement3

The switch statement acts like an if-elseif-else statement. The switch statement is executed in order statement by statement. Only when the value of the expression in the switch matches the value in a case statement that execution begins and the execution continues until the end of the switch or the first break statement.

   switch ($i)
   {
      case 0:
         echo "zero"; 
         break;
      case 1: 
         echo "one"; 
         break;
      default: 
         echo "Out of range"; 
         break;
   }

Loops

while, do-while, and for loops behave exactly like their counterparts in C and Java. The syntax is as follows:

   while (expr)
   {

   }

   do
   {

   } while (expr);

   for (init; expr; incr)
   {

   }

foreach works only on arrays and will allow you to iterate over the elements of the array.

   foreach (array as $value)
      statement

   foreach (array as $key => $value)
      statement

In the first form it loops over the elements of array and the value of the current element is assigned to $value. In the second form the current element's key will be assigned to $key on each iteration of the loop.

Functions

A function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. Functions need not be defined before they are referenced. A function definition can be inside another function. All functions have global scope - they can be called outside a function even if they are defined inside. PHP does not support function overloading and it is not possible to redefine previously declared function. Both variable number of arguments and default arguments are supported in functions. It is also possible to call a function recursively. Functions that do not return any value will return NULL as the result. Here is the syntax for a function:

   function foo ($arg1, $arg2, ..., $argn)
   {
      // perform computation
     return $retval;
   }

PHP supports passing arguments by value so that if the value of the parameter is modified within the function it does not get changed outside the function. To modify a parameter within a function it must be passed by reference. Prepend the ampersand (&) before the name of the parameter.

   $x = 1;
   function foo (&$x)
   {
      $x = 2;
   }
   // $x is 2

You can set default values to parameters. The default values must be constant expressions. When using parameters with default values, all parameters having default values should be on the right of all parameters not having default values.

   function foo ($a, $b, $x = 1, $y = "hello")
   {
      ....
   }

PHP has support for variable-length argument lists in user defined functions.

   function foo ()
   {
      $numargs = func_num_args();
      echo "Number of arguments: $numargs <br /> \n";
      if ($numargs >= 2)
      {
         echo "Second argument is: " . func_get_arg(1) . "<br /> \n";
      }
      $arg_list = func_get_args();
      for ($i = 0; $i < $numargs; $i++)
      {
         echo "Argument $i is: " . $arg_list[$i] . "<br /> \n";
      }
   }

Enhanced Error Checking

PHP has the ability to provide error messages at runtime, but by default, these are turned off. In general, web developers prefer not to air their dirty laundry to users, and instead have their PHP code fail invisibly.

To set which classes of PHP errors you want to report, use the function error_reporting():

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors
error_reporting(E_ALL);

Another function, ini_set(), is used to set the value of a configuration option. The function call

ini_set("display_errors", "on");

causes the errors reported by the error_reporting() function to be displayed. Thus, while you're writing and debugging your PHP scripts, it is a good idea to include the following two statements at the top of your PHP code:

<?php
   error_reporting(E_ALL);
   ini_set("display_errors", "on");
       . . .