Introduction to PHP

PHP used to be an acronym for Personal Home Page. Now only the acronym remains but not the original name. It was created by Rasmus Lerdorf in the mid 1990's. It is a server side XHTML-embedded scripting language. When the server is requested an XHTML page with embedded PHP code, it calls the PHP interpreter and processes the document and sends the output of processing the script in an XHTML page.

The PHP interpreter will merely copy any XHTML or JavaScript code that it sees in a PHP document file and it will interpret any PHP code and embed the results in the output file. The syntax of PHP is similar to JavaScript. It uses dynamic typing - i.e. variables do not have any intrinsic type nor is the type declared. The type of a variable is the type of the value it is assigned.

How to Include PHP Code?

PHP code is embedded in an XHTML document between the <?php and ?> tags. Here is an example of a PHP embedded XHTML code. The file has a .php extension instead of the .html extension.

<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 of comment.

# Here is another single line of 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 is a dynamically typed language. The type of a variable is the type of the value that is assigned to it. PHP recognizes these 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 value NULL associated with it. That is the only value of the NULL type. To test if a variable has been assigned a valued you can use the function isset(). The function isset( $x ) will return true if $x has been assigned a value and 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: is platform dependent but usually is 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 character is the same as a byte. The string could be any length. The only limit is the available memory of the computer.

The simplest way to express a string is to enclose it in single quotes ('). To specify a literal single quote escape it with a backslash (\). Variables and escape sequences for special characters will not be interpreted when they are embedded in single quotes.

When a string is enclosed in double quotes variables and escape sequences are interpreted.

The third way of expressing strings is the heredoc format: <<<. After this operator (<<<) an identifier is provided and then newline. The string then follows and then the same identifier to close the quotation. The closing identifier must begin the first column of the line. The line containing the closing identifier must contain no other characters except possibly a semicolon. The identifer may not be indented and there may not be any spaces or tabs before or after the semicolon. The identifer follows the naming conventions of variables in PHP. 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. The values in an array can be other arrays. So multidimensional arrays can be defined in PHP. 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. 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.

<?php
$arr = array(10 => false, "foo" => "bar");
$arr = array("arr" => array (6 => 5, 13 => 9, "a" => 42));
// This array is the same as ...
array (5 => 43, 32, 56, "b" => 12);
// ... this array
array (5 => 43; 6 => 32, 7 => 56, "b" => 12);
?>

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 (""). An empty bracket is not an empty string. Arrays and objects cannot be used as keys. An existing array can be modified by explicitly setting values in it. This is done by assigning values to the array by specifying the key is square brackets. The key may also be omitted.

$arr[key] = value;
$arr[] = value;

If the array does not exist it will be created. So this is another way of creating an array. To change a value, assign another value with that key. To remove a key/value pair call unset().

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

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

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

unset ($arr[5]);  // Removes this element 

unset ($arr);  // Removes the array
?>

If a key that already has a value is specified, that value will be overwritten. If a key is not specified then the maximum integer key since last re-indexing is taken and the new key will be that maximum value plus 1.

<?php
$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;
?>

These are 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.

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;
So $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).

Comparison 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

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`;

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

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");

Logical operators:

Example Name 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 || TRUE if either $a or $b is TRUE
and, xor, or have lower precedence than the assignment operator (=). ! (not), && (and), || (or) have higher precedence than the assignment operator.

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

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. The following is an example of a nested condtional:

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

The switch statement acts like a nested 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:

<?php
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 function.

<?php
$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.

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

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

<?php
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";
  }
}
?>