TABLE OF CONTENTS (HIDE)

Getting Started with PHP

(not for the dummies)

Introduction

PHP is a popular open-source general-purpose HTML-embedded server-side scripting language, which enables web developers to create dynamically generated web pages quickly. PHP was originally created by Rasmus Lerdorf in 1995, who added web forms that communicate with database (based on CGI/Perl) and called it "Personal Home Page/Forms Interpreter" or PHP/FI. PHP is now said to stand for "PHP: Hypertext Preprocessor" (a recursive acronym similar to GNU - GNU is Not Unix). PHP is now maintained by "The PHP Group" (@ http://www.php.net).

PHP is great for a one-man-operated (or two-man-operated) project, where a technically proficient geek can quickly produce a working prototype for a webapp. However, it is hard to use PHP to write good MVC (Model-View-Control) webapp, where the data (model), presentation (view) and logic (control) are well separated to facilitate team collaboration and maintenance. There are many PHP MVC frameworks (or libraries that run on top of PHP), such as Zend, CakePHP, Yii, Symfony and CodeIgniter. However, the learning curve of using these frameworks could be steep.

Other HTML-embedded server-side scripting languages are: Microsoft's ASP (Active Server Pages), Java's JSP (Java Server Pages), CGI/Perl and etc.

Modes of Operation

PHP operates in two modes:

  1. Standalone Command-line Interface (CLI): You can run a CLI PHP script by itself, just like any program written in Perl/Python or C/C++/Java.
  2. HTML-embedded Server-side Script: The server-side script must be run under a PHP-capable Web Server (such as Apache HTTP Server).

We shall focus on PHP Server-side script, as it is what PHP is most often used.

Pre-Requisites

This article is NOT for the dummies. The pre-requisites are:

  • HTML
  • For webapps: HTTP, HTML/CSS/JavaSCript/Ajax and MySQL.
  • For OOP: basic knowledge of OOP.

Installing PHP

PHP is most often used in writing HTML-embedded server-side scripts, that run inside an PHP-capable Web Server, such as Apache HTTP Server. Hence, to setup PHP for server-side scripting, you need to set up a PHP-capable web server. In addition, PHP scripts often communicate with database (such as MySQL) to generate dynamic web pages.

Read "Setting Up Apache/MySQL/PHP (AMP) for Linux, Windows and Mac".

Getting Started with PHP Server-side Scripts by Examples

Let's begin with the PHP server-side scripts. We shall discuss PHP standalone script (CLI) in the next section.

Example 1: First PHP Hello-world Program

Use a programming text editor (such as NotePad++ for Windows, or gedit for Ubuntu/Mac OS X) to create the following PHP script and save as "hello.php" under your web server's document root directory (e.g, "www" for WampServer. "htdocs" for XAMPP):

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My First PHP Web Page</title>
</head>
<body>
<?php
// First PHP script to say hello
echo '<h1>Hello, world!</h1>';
?>
</body>
</html>

To run this script, start a browser and issue URL http://localhost/hello.php, assuming that the HTTP server has been started on the default TCP port 80.

By default, PHP script has a file extension of ".php". When the web server encounters a request for a ".php" file, it passes the ".php" file to a PHP processor. A PHP script is typically a HTML file with embedded PHP commands enclosed within <?php .... ?> tag. The PHP processor processes the PHP commands. The results are then merged into the HTML file, and returned to the client (web browser).

In the above example, the PHP's echo command outputs the given string.

Try "View Source" to check the output received by the client:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My First PHP Web Page</title>
</head>
<body>
<h1>Hello, world!</h1></body>
</html>

It is important to take note that the <?php ... ?> tag (and its contents) are not returned to client as it is. Instead, it is processed in the server, and the output returned to the client.

In brief:

  1. PHP can be used as server-side script. The server processes the PHP script and returns its output.
  2. PHP server-side script is HTML-embedded.

Example 2: phpinfo() Built-in Function

Enter the following script and save as "RunPhpinfo.php", under your web server's document root directory:

<?php 
// Run phpinfo() built-in function
phpinfo();
?>

Run the script from a web browser via http://localhost/run_phpinfo.php.

The PHP's built-in function phpinfo() outputs a fully-formatted HTML page showing the details of your PHP environment.

Example 3: Computation

You can write a PHP script to perform computation, just like a C/C++/Java program. For example, create the following PHP script called "PrintTimeTable.php" and run the script.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Simple Computation</title>
</head>
<body>
<?php
// Simple Computation
$size = 9;
echo '<pre>';
for ($row = 1; $row <= $size; ++$row) {
   for ($col = 1; $col <= $size; ++$col) {
      printf('%3d', $row * $col);
   }
   echo '<br>';
}
echo '</pre>'
?>
</body>
</html>
How it Works?
  1. A PHP variable begins with a '$' sign. Like all the other scripting languages, PHP is loosely-type. You do not have to declare the type/name of a variable before using it. The variable will take on the type of the value assigned.
  2. You can use the echo statement to output a string. You can also use the C-like printf() for formatted output.
  3. The for-loop syntax is exactly the same as C/C++/Java.

Example 4: Handling HTML Form Data

Create the following script and save as "FormTest.php":

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test HTML Form</title>
</head>
<body>
<?php
if (isset($_POST['username'])) {
   echo '<h2>Hello, ' . htmlentities($_POST['username']) . '</h2>';
}
?>
<form method="post">
<label>What is your name? <input type="text" name="username"></label><br>
<input type="submit">
</form>
</body>
</html>
How it works?
  1. An HTML form is defined (Lines 13-16) having a text field with a name called username (Line 14). This form uses POST method with default action to the current page.
  2. In the PHP script (Lines 7-11), the system variable $_POST is an associative array keeping all the key-value pairs of the POST request parameters - in this example, username=value. $_POST['username'] gets the value of the key username. The built-in function isset($_POST['username']) returns TRUE, if the value of the given key is set. During the first visit, the key username is not set in the POST request parameters. Hence, the hello message is not displayed. Once user enters the name and submit the form, username is set; and the hello message will be displayed.
  3. In the echo command (Line 9), the dot (.) operator concatenates two strings; the built-in function htmlentities(str) (or htmlspecialchars(str)) converts all the special characters to HTML entities (e.g., > to &gt;, < to &lt;, " to &quot;, & to &amp;). It is important to convert special characters, in particular, < and >, before echoing back to the client to prevent the so-called Cross-Site Scripting attack (XSS).
  4. Try "View Source" to check the output produced by the PHP script.

[TODO] More basic examples

Running PHP Scripts as Standalone Programs

Instead of using PHP to write server-side scripts that run under an HTTP server, you can also use PHP to write a stand-alone program, known as CLI (Command-Line interface).

You can skip this section if you are not interested in writing standalone PHP scripts.

Running PHP Scripts From Command-line

For example, prepare the following PHP script and save as "hello.php":

<?php
echo "Hello, world!\n";
?>

To run the PHP Script:

$ php hello.php
Hello, world!

By default, PHP reads the program from the stdin. Hence, you could input the statements on command-line and press Ctrl-D to signal end-of-file:

$ php
<?php
echo "Hello, world!\n";
?>[Ctrl-D]
Hello, world!

You can also run PHP statements via the -r option (run). For example,

$ php -r 'echo "Hello, world!\n";'
Hello, world!
 
$ php -r 'phpinfo();' | less
......
Prompting for User input

You can use the readline() function to prompt for user input from command-line. For example,

1
2
3
4
5
6
7
8
9
10
<?php
// Simple Computation
$size = readline('Enter the size of table: ');
for ($row = 1; $row <= $size; ++$row) {
   for ($col = 1; $col <= $size; ++$col) {
      printf('%3d', $row * $col);
   }
   echo "\n";
}
?>

Unix PHP Shell Script

In Unix, you can make a PHP script as an executable script by adding the so-called she-bang line "#!/usr/bin/php", specifying the location of PHP interpreter; and enabling the executable file mode. For example, create the following file called "HelloExe.php":

#!/usr/bin/php
<?php
echo "Hello, world!\n";
?>
// Set the file executable
$ chmod u+x HelloExe.php
// Execute the script
$ ./HelloExe.php
Hello, world!

Eclipse PHP Developer Tool (PDT)

A good IDE with a graphic debugger is critical for program development.

Eclipse PDT (PHP Developer Tool) is an IDE for PHP program development. The main advantage is it can debug PHP script with XDebug or Zend Debugger. Read "Setting up Eclipse PDT (PHP Developer Tool)"

PHP Language Syntax

PHP is typically used together with JavaScript in a webapp. Take note and remember that PHP syntax is quite different from JavaScript (which follows Java, and hence C/C++). For example, in PHP, a variable name starts with a '$' sign; there is no var keyword to declare a variable; an array is defined via array('1', '2', '3') (or ['1', '2', '3'] in PHP 5.4) instead of {'1', '2', '3'}; an associate array is defined via array('name' => 'peter', 'age' => 18) instead of {name:'peter', age:18}; and many more.

Basic object-oriented features was added in PHP 3, improved in PHP 4, and completely rewritten in PHP 5.

The official "PHP Language Reference" is available @ http://php.net/manual/en/langref.php.

Basic Syntax

Comments

A mutli-line comment is enclosed within /* and */. An end-of-line comment begins with // (or #) and lasts till the end of the current line. Comments are ignored by the PHP processor, but they are important in providing explanation and documentation for you and your readers. I recommend using comments liberally.

Statement

A statement performs a single piece of programming action. A PHP statement ends with a semicolon (;). A block, consisting of zero or more statements, is enclosed within braces {}. A block is treated as one unit and can be used as the body of constructs such as if-else and loops.

Whitespaces

Additional whitespaces (blank, tab and newline) are ignored. I strongly recommend that you use additional whitespaces to format your code, so that it can be understood by you and your readers.

Case Sensitivity

PHP is case sensitive.

Output: echo and print

You can use the "echo" or "print" to produce output.

void echo (string $arg1 [, string $... ])
int print (string $arg)  // always return 1

"echo" accepts one or more strings (separated by commas); whereas "print" takes only one string. "echo" is more commonly used than "print"

For example,

<?php
// echo one string.
echo 'Hello, world!<br>';
// Parentheses are optional.
echo('Hello, world!<br>');
 
// You can echo multiple strings (separated by commas).
echo 'one', ' ', 'two', ' ', 'three', '<br>';
// You can also use the string concatenation operator dot (.) to join the strings into one.
echo 'one' . ' ' . 'two' . ' ' . 'three' . '<br>';
 
print 'Hello, world!<br>';
print('Hello, world!<br>');  // parentheses are optional
print 'one' . ' ' . 'two' . ' ' . 'three' . '<br>';  // one string
?>

"echo" and "print" are not really functions, they are program constructs. Hence, the parentheses are optional.

Output functions for Debugging: var_dump(), print_r() and var_export()

These functions can be used to display information about a variable. They are particularly useful for display complex variables such as array and object.

  • var_dump(var): dumps detail information about a variable, useful for debugging.
  • var_export(var): export the value of the variable in valid PHP codes.
  • print_r(var): similar to var_export(), but print in human readable form.
  • print_r(var, TRUE): return the generated string instead of printing it.
Formatted Output Functions: printf() and sprintf()
  • printf(formatString, var, ...): similar to C's printf().
  • sprintf(formatString, var, ...): returns the formatting string, instead of sending it to the output.
Expressions

An expression is a combination of variables, literal values and operators, that can be evaluated to produce a value.

Variables

A PHP variable begins with a dollar sign '$'.

PHP is a loosely-type (or weakly-type) language. You do not have to declare the type of a variable before using the variable. You can simply assign a literal value, and the PHP processor will set the type of the variable accordingly.

For example,

<?php
// Integer
$myInteger = 123;
echo $myInteger, '<br>';
 
// Floating point number
$myFloat = 45.67;
echo $myFloat, '<br>';
 
// a single-quoted string
$myString = 'hello';
echo $myString, '<br>';
 
// An array of string
$myArray = array('Mon', 'Tue', 'Wed');
echo $myArray[0], '<br>';
echo $myArray[1], '<br>';
echo $myArray[2], '<br>';
?>

Variable Naming Rules: A variable name can contain letters (a-z, A-Z), digit (0-9) and underscore (_). It shall begin with a letter or underscore. Variable names are case-sensitive, i.e., a $rose is NOT a $ROSE, and is not a $Rose.

Variable Naming Convention: A variable name shall be a noun comprising one or more words. You can either use Java-style or C-style:

  • Java-style: begins with lowercase, with subsequent words initial-capitalized (called camel-case).
  • C-style: all words in lowercase, and joined with underscores.

On the other hand, constants are in uppercase, with words joined with underscores.

Assignment Operator (=)

You can use the assignment operator (=) to assign a value into a variable.

Strings

Single-quoted and Double-quoted Strings

There are two types of string literals: single-quoted and double-quoted.

  • A single-quoted string preserves its content as it is. It does not interpret escape sequences, e.g., '\n' will be treated as a back-slash followed by n (2 characters); not the newline character (1 ASCII character 0AH). You can place double-quote directly inside the single-quoted string, e.g., 'Hi, "Peter"'. To place a single-quote, use escape sequence \', e.g., 'Hi, \'Peter\''. To place a backslash \, use double backslashes \\ to avoid ambiguity. In brief, there are only two escape sequences in single-quoted string, \' for single-quote and \\ for backslash.
  • A double-quoted string performs variable substitution (or variable evaluation) and interprets all escape sequences starting with backslash \ (such as \t for tab, \n for newline and \r for carriage return, \" for double-quote, \\ for backslash, etc.).

For example,

<?php
$count = 5;
echo "<p>The count is $count.\n</p>";        // Substitute variable with its value
echo '<p>The count is $count.\n</p>';        // As it is
echo '<p>The count is ' . $count . '.</p>';  // Use string concatenation (.)
echo '<p>The count is ', $count, '.</p>';    // echo multiple items
echo "<p>The count is " . $count . ".</p>";
?>
The count is 5.[newline]
The count is $count.\n
The count is 5.
The count is 5.
The count is 5.

Double-quoted string facilitates variable substitution (in place of tedious string concatenation) and interpretation of escape sequences. Use single-quoted strings, which are more efficient, if variable substitution and escape sequences are not needed.

In variable expansion, PHP greedily parse as many characters as possible (after the $ sign) to form the variable name. You may enclose the variable name in braces {} to explicitly delimit the name. For example,

<?php
$drink = 'coffee';
echo "Give me one $drink.<br>";
echo "Give me two $drinks.<br>";    // won't work, treated as variable $drinks
echo "Give me two {$drink}s.<br>";
?>

You cannot expand the return value of a function via double-quoted string - concatenation needed. For example,

<?php
echo 'phpinfo() is ' . phpinfo();
// PHP cannot expand function inside double-quoted string
// echo "phpinfo() is {phpinfo()}";
?>
String Concatenation Operator (.)

You can join two strings via the string concatenation operator (.).

Notes: JavaScript (and Java) uses '+' as string concatenation operation. '+' don't work in PHP, which is one of the most common bugs in writing webapp using PHP and JavaScript together!

Multiline Strings, Heredoc and Nowdoc

In PHP, a single-quoted string and double-quoted string can span multiple lines, e.g.,

<?php
$message1 = 'Hello';
$message2 = 'world';
 
// Multiline double-quoted string
echo "<h1>This is a multiline string</h1>
<p>First Line</p>
<p>$message1,\t$message2</p>
<p>Take note that variables/Escape characters are expanded.</p>
<p>Last     Line</p>";   // closing double-quote here
 
// Multiline single-quoted string
echo '<h1>This is a multiline string</h1>
<p>First Line</p>
<p>$message1,\t$message2</p>
<p>Take note that variables/Escape characters are NOT expanded.</p>
<p>Last     Line</p>';   // closing single-quote here
?>

Try "View Source" to check the output. All the newlines and whitespaces are preserved within the quotes. Again, double-quoted string performs variable substitution; whereas single-quoted string does not.

You can also use the so-called heredoc (here-document) syntax for double-quoted multiline string (since PHP 5.3). For example,

<?php
$message1 = 'Hello';
$message2 = 'heredoc';
$output = <<<_END
<h1>This is a multiline string</h1>
<p>First Line</p>
<p>$message1,\t$message2</p>
<p>Take note that variables/Escape characters are expanded.</p>
<p>Last Line</p>
_END;
echo $output;
?>

Heredoc (<<<tag ... tag) is treated as a double-quoted string. The begin tag must follow by a newline. The end tag must begin at the first column and shall occupy the entire line with nothing after the tag - no even a comment. Instead of the tag-name _END, you can choose any tag-name such as _EOD, END, OUTPUT, and etc. The tag name shall begin with a letter or underscore, and consists of letters, digits or underscore.

Similarly, you can use the so-called nowdoc (now-document) syntax (<<<'tag' ... tag) for single-quoted string, where the begin-tag is single-quoted (since PHP 5.3). For example,

<?php
$message1 = 'Hello';
$message2 = 'nowdoc';
$output = <<<'_END'
<h1>This is a multiline string</h1>
<p>First Line</p>
<p>$message1,\t$message2</p>
<p>Take note that variables/Escape characters are NOT expanded.</p>
<p>Last Line</p>
_END;
echo $output;
?>

Multiline strings, heredoc and nowdoc are convenient to produce an entire web page, which is the goal of PHP; instead of using a echo statement per line - as in C/C++/Java. Furthermore, there is no need to use escape characters for quotes.

Built-in String functions
  • strlen(str): returns the length of the given string.
  • substr(str, start [, length]): returns the substring from start position of length.
  • strtoupper(str), strtolower(str): return the uppercase/lowecase of the given string.
  • trim(str): trim whitespaces from the beginning and end of the given string.
  • rtrim(str): trim whitespaces from the end of the given string.
  • [TODO]

String and Regular Expression (regexe)

Regular Expression (regexe) is a power tool and is essential in program development.

Built-in Regexe functions
  • preg_match(...): [TODO]
  • preg_replace(...): [TODO]
  • preg_split(...): [TODO]
  • [TODO]

[TODO]

Data Types

As mentioned, PHP is a loosely-type language (similar to other scripting languages such as Perl and JavaScript). You do not have to explicitly declare the type of variables. PHP will infer the data type from the value assigned and convert variables to the types needed in operations.

PHP supports these data types:

  1. integer: platform-specific (such as 32-bit or 64-bit).
  2. double: also platform-specific (single-precision or double-precision).
  3. string: single-quoted, double-quoted, nowdoc, and heredoc.
  4. boolean: PHP supports native boolean type, which takes value of either TRUE or FALSE. In type casting and conversion, these values are considered boolean FALSE:
    • integer 0,
    • float 0.0,
    • empty string '' and string '0',
    • an array with zero element (empty array),
    • an object with zero member variables,
    • the special value NULL (indicating no value).
    Take note that string 'FALSE' is evaluated to boolean TRUE in PHP. Hence, if you need to use string to represent boolean (e.g. in HTML <select> or radio buttons' values), use '0' for false, and '1' for true, instead of string 'true' and 'false', which requires some explicit conversions.
    The PHP manual states that boolean literals should be written in uppercase TRUE and FALSE, but PHP also accepts lowercase. I suggest you use uppercase for consistency and readability. (Take note that JavaScript and Java use lowercase.)
  5. object: an instance of a class.
  6. resource: represents external resources, such as image, file, database.
  7. array: array of the above types.
  8. Type null and value NULL: A special value NULL is used to represent a variable with no value. The value NULL is the only possible value of type null.
    A variable is considered to be NULL if
    • it has been assigned the value NULL;
    • it has not been set to any value yet;
    • it has been unset().
    Again, I suggest that you use uppercase for NULL value. (Take note that JavaScript and Java use lowercase.)
gettype() and is_xxx()

To find the type of a variable, use function gettype(). You can also use boolean function is_xxx(var) (e.g., is_integer(), is_int(), is_double(), is_string(), is_array(), is_object()) to check if a variable belongs to a certain type.

For example,

<?php
$myInt = 5;
$myDouble = 1.23;
$myString = 'Hello';
$myBoolean = TRUE;
$myArray = array('Mon', 'Tue', 'Wed');
$myNull = NULL;
 
// gettype()
echo gettype($myInt), '<br>';       // integer
echo gettype($myDouble), '<br>';    // double
echo gettype($myString), '<br>';    // string
echo gettype($myBoolean), '<br>';   // boolean
echo gettype($myArray), '<br>';     // array
echo gettype($myNull), '<br>';      // NULL
 
// is_xxx()
echo is_integer($myInt), '<br>';    // 1 (TRUE)
echo is_string($myInt), '<br>';     // nothing (FALSE)
 
// Type Casting
echo gettype((string)$myDouble), '<br>';  // string
echo gettype((double)'1.234'), '<br>';    // double
?>
Debugging: var_dump(), var_export() and print_r()

These functions can be used to display information about a variable. They are particularly useful for display complex variables such as array and object.

  • var_dump(var): dumps detail information about a variable, useful for debugging.
  • var_export(var): export the value of the variable in valid PHP codes.
  • print_r(var): similar to var_export(), but print in human readable form.
  • print_r(var, TRUE): return the generated string instead of printing it.

For example,

<?php
$myInt = 5;
var_dump($myInt);
echo '<br>';
var_export($myInt);
echo '<br>';
print_r($myInt);
echo '<br>';

$myString = 'Hello';
var_dump($myString);
echo '<br>';
var_export($myString);
echo '<br>';
print_r($myString);
echo '<br>';

$myArray = array('Mon', 'Tue', 'Wed');
var_dump($myArray);
echo '<br>';
var_export($myArray);
echo '<br>';
print_r($myArray);
?>
int 5      // var_dump()
5          // var_export()
5          // print_r()

string 'Hello' (length=5)  // var_dump()
'Hello'                    // var_export()
Hello                      // print_r()

array (size=3)                                 // var_dump()
  0 => string 'Mon' (length=3)
  1 => string 'Tue' (length=3)
  2 => string 'Wed' (length=3)
array ( 0 => 'Mon', 1 => 'Tue', 2 => 'Wed', )  // var_export()
Array ( [0] => Mon [1] => Tue [2] => Wed )     // print_r()
Checking Variables

You can use the following built-in functions:

  • isset($var): return TRUE is $var is set and is not NULL.
  • unset($var): unset the $var.
  • is_null($var): return TRUE if the $var is NULL.
  • empty($var): return TRUE if the $var does not exist (i.e. !isset($var)) or its value is equivalent to boolean FALSE (e.g., NULL, 0, 0.0, '', '0', empty array and object).
Type Casting and Conversion

As an example, there are 3 ways to cast a string to an integer:

  1. intval(): The function intval($str) returns an equivalent integer or 0 if $str does not contain an valid integer. Take note that it cannot handle '0', as the result is ambiguous.
  2. Casting operator (int): same as intval().
  3. settype($var, 'integer'): convert $var to integer type, and return either TURE/FALSE.

Operators

Type casting Operators

You can use the type casting operator to get a value of the desired type:

Operator Meaning Example
(integer), (int) Cast to an integer  
(boolean), (bool) Cast to a boolean  
(double), (float), (real) Cast to a floating-point number  
(string) Cast to a string  
(array) Cast to an array  
(object) Cast to an object  
Arithmetic Operators for Numeric Types
Operator Meaning Example
+ Addition  
- Subtraction  
* Multiplication  
/ Division  
% Modulus (Remainder)  
++ Increment (unary)  
-- Decrement (unary)  
Shorthand Assignment Operators
Operator Meaning
+= $x += $y is the same as $x = $x + $y
-= $x -= $y is the same as $x = $x - $y
*= $x *= $y is the same as $x = $x * $y
/= $x /= $y is the same as $x = $x / $y
%= $x %= $y is the same as $x = $x % $y
.= $x .= $y is the same as $x = $x . $y
(String Concatenation)
Comparison (Relational) Operators
Operator Meaning Example
== is equal to  
!= is not equal to  
=== is strictly equal to (both type and value)  
!== is not strictly equal to (both type and value)  
> is greater than  
>= is greater than or equal to  
< is less than  
<= is less than or equal to  

Similar to JavaScript, PHP provides two sets of equality operators: == and ===. The === compares both the value and the type. For example,

<?php
$n = 8;
$str = '8';

var_dump($n == $str);    // bool(true)
var_dump($n === $str);   // bool(false) difference types
?>

It is highly recommended to use === and !==, to avoid some unexpected comparison results caused by type casting (e.g., 'FALSE' == FALSE gives FALSE, as string 'FALSE' is casted to boolean TRUE).

Logical (Boolean) Operators
Operator Meaning Example
&& Logical AND  
|| Logical OR  
! Logical NOT  
and Low-precedence Logical AND  
or Low-precedence Logical OR  
xor Low-precedence Logical Exclusive OR  

There are two sets of logical operators: "and" vs. "&&". They carry out the same task but having different operator precedences. "&&" is higher than assignment; while "and" is lower. Hence,

$n = $a and $b;
// interpret as ($n = $a) and $b;

$n = $a && $b;
// interpret as $n = ($a && $b);

It is recommended to use "and" "or" as they are human readable, but take note of their precedence over assignment.

Notes: JavaScript (and Java) does not support "and" "or" operators.

The logical chained operations are short-circuited. For example,

!$error
   or die('error encountered');   // only run if $error is TRUE
   
$pStmt->bind_param(...)
   and $pStmt->execute(...)
   and $pStmt->store_result(...)
   and $pStmt->bind_result(...)
   or die('error encountered');   // run only if any of the above is FALSE
Constants

You can define a constant via the define command and refer a a constant without the leading $ sign.

// Syntax
define(CONSTANT_NAME, value);
 
// Example
define('USERNAME', 'Peter');
$currentUser = USERNAME;    // without leading $ sign

Constant Naming Convention: A constant is a noun comprising one or more words. Constants are in uppercase, with words joined with underscores.

Constants are not expanded inside the double-quoted strings. You need to use the string concatenation operator (.) to join constants with other strings.

Control Structures

Conditional Flow Control
Syntax Example
// if-then
if (test) {
   trueBlock;
}
 
// if-then-else
if (test) {
   trueBlock;
} else {
   falseBlock;
}
 
// Shorthand if-else expression
// Return the value of trueExpression if the test is TRUE;
// Otherwise, return the value of falseExpression
test ? trueExpression : falseExpression;
 
// Shorthand ternary
// Since PHP 5.3, you can write:
expr ?: value-if-false
   // same as "expr ? expr : value-if-false" (i.e., leaving out the middle part)
 
// nested-if
if (test1) {
   block1;
} elseif (test2) {
   block2;
} elseif (test3) {
  .......
} else {
   elseBlock;
}
 
// switch-case
switch (selector) {
   case value1: block1; break;
   case value2: block2; break;
   ......
   default: defaultBlock;
}
 
// Alternative switch-case syntax
switch (selector):
   case value1: block1; break;
   case value2: block2; break;
   ......
   default: defaultBlock;
endswitch;
 
Loop Flow Control
Syntax Example
// while loop
while (test) {
   trueBlock;
}
 
// do-while loop
do {
   trueBlock;
} while (test);
 
// for loop
for (initialization; test; post-processing) {
   trueBlock;
}
 
break;   // Breaking out the innermost loop
 
continue;  // Skip the rest of statements and 
           // continue to the next iteration of the loop
 
// Do the body for each element of an array
foreach (arrayVar as itemVar) {
   body;
}
 
The include and require Statements
  • include: the include statement tells the PHP processor to fetch the file and load its contents.
  • include_once: to include the file only once. It is recommended to use include_once, instead of include.
  • require and require_once: The require is identical to include, except that it handles errors differently. If an error occurs, the include generates a warning, and continues executing the script. The require generates a fatal error, and terminates the script.
  • require_once is recommended.
exit and die

"exit str" echos the str and exit the script. "die(str)" does the same thing.

"exit" is a PHP construct instead of a function, hence, you can write "exit str". But "exit(str)" is also acceptable.

Indexed Arrays and Associative Arrays

An array is a collection of elements (not necessarily of the same type - as PHP is lossy-type).

To define and initialize an array, array(elm1, elm2, ..., elmN). Staring with PHP 5.4, you can also use simpler square brackets in the form of [elm1, elm2, ..., elmN]. For examples,

<?php
$a1 = array('a', 2, 'c', TRUE);  // mixed contents
var_dump($a1);
// array(4) {
//   [0]=> string(1) "a"
//   [1]=> int(2)
//   [2]=> string(1) "c"
//   [3]=> bool(true)
// }
 
// From PHP 5.4, use simpler square bracket [], instead of array()
$a2 = ['a', 2, 'c', TRUE];
var_dump($a2);
 
// You can include the trailing commas without causing syntax error!
$a3 = ['a', 2, 'c', TRUE,];
var_dump($a3);
?>

To reference an element of an array, use arrayName[index]. The index begins at 0. This type of array is also called Indexed Array.

In PHP, arrays are dynamically sized. To insert element into an array, you can explicitly provide the index number, or leave it empty. The new element will be appended to the end of the array.

For example,

<?php
$a1 = ['zero', 11, 2.2];
var_dump($a1);   // Index 0 to 2
 
// Append elements to the end of an array
// PHP's arrays are dynamically allocated
$a1[] = 'three';  // Index 3
$a1[] = 'four';   // Index 4
$a1[7] = 'seven'; // Skip indexes 5 and 6
 
// Referencing elements of an array (missing indexes cause errors)
for ($i = 0; $i <= 7; ++$i) {
   echo "$a1[$i], ";
}
echo "\n";
 
// Use the foreach loop (missing indexes are skipped)
foreach($a1 as $item) {
   echo "$item, ";
}
?>

Take note that:

  1. The elements need not of the same type.
  2. The size is dynamically adjusted for new elements.
  3. The index need not be contiguous. But you cannot use the missing indexes. This is because PHP's array is actually an associate array with integer key - to be described in the next section.
  4. It is convenient to use var_dump() to display the detail content of an array, which is handy in debugging.
Built-in Array Functions
  • is_array($var): returns TRUE if $var is an array.
  • count($array): returns the number of elements in the given array.
  • in_array($value, $array): returns TRUE if the array contains the given value.
  • sort($array), sort($array, SORT_NUMERIC), sort($array, SORT_STRING): sort the elements of the given array. sort() operates on the array directly (by reference).
  • rsort($array, SORT_NUMERIC), rsort($array, SORT_STRING): sort in reverse order.
  • shuffle($array): put the elements in random order. shuffle() also operates on the array directly.
  • implode($glue, $array): join the array elements with the $glue string. For example,
    $a = array('apple', 'orange', 'banana');
    echo implode('|', $a);
       // apple|orange|banana
  • explode($delimiter, $str): takes a string and tokenizes into an array based on the delimiter.
    <?php
    $days='Mon,Tus,Wed,Thu';
    $dayArray = explode(',', $days);
    var_dump($dayArray);
    ?>
    array (size=4)
      0 => string 'Mon' (length=3)
      1 => string 'Tus' (length=3)
      2 => string 'Wed' (length=3)
      3 => string 'Thu' (length=3)
  • array_push($array, $value1, $value2,...): pushes one or more elements to the end of the array. If there is only one element, you can use "$array[] = value".
  • array_pop($array): pops the last element off the array.
  • array_shift($array): shift an element off the beginning of the array.
  • array_unshift($array, $value1, $value2,...): prepend one or more elements at the beginning of the array.
  • reset($array), end($array): returns the first element and last element of the array, respectively.
Associative Arrays

An associative array is a collection of key-value pairs (or name-value pairs). Unlike array, which is indexed by a numeric integer, an associative array is index by a key-string. To initialize an associative array, use array(key1=>value1, key2=>value2, ...). To reference an element, use arrayName[key]. For example,

<?php
// Define and initialize an associative array
$myAssoArray = array('one'=>'Monday', 'two'=>'Tuesday', 3=>33.33);
var_dump($myAssoArray);
 
// Insert new element. Again, associative array are dynamically allocated
$myAssoArray['four'] = 'Thursday';
 
// Referencing elements of an associative array
echo $myAssoArray['one'] . '<br>';
echo $myAssoArray[3] . '<br>';
 
print_r($myAssoArray);   // print in readable format
echo '<br>';
 
// Use the foreach loop (missing indexes are skipped)
foreach($myAssoArray as $key => $value) {
   echo "$key: $value<br>";
}

// You can use isset() function to check if a key exists (assigned a value)
echo (isset($myAssoArray['four']) ? 'Key "four" is set' : 'Key "four" is NOT set') . '<br>';
echo (isset($myAssoArray['five']) ? 'Key "five" is set' : 'Key "five" is NOT set') . '<br>';
 
// Use unset() to remove a key-value pair
unset($myAssoArray['four']);
var_dump($myAssoArray);
?>

Take note that PHP does NOT differentiate between Indexed Array and Associative Array.

Built-in Associative-Array Functions
  • isset($var): Return TRUE if the given var is set and is not NULL, e.g. isset($a['first']).
  • array_key_exists($key, $array): Return TRUE if the given key is set (possibly having NULL value).
  • unset($var): unset the given var, e.g., unset($a['first']).
  • extract($array): extract each element of the given associative array and turn them into variables, e.g., the element 'one'=>'Monday' will be extracted as $one='Monday'.
    <?php
    $dayArray = array('one' => 'Monday', 'two' => 'Tuesday', 'three' => 'Wednesday' );
    extract($dayArray);
    var_dump($one);
    var_dump($two);
    var_dump($three);
    ?>
    string 'Monday' (length=6)
    string 'Tuesday' (length=7)
    string 'Wednesday' (length=9)
  • compact($var1, $var2, ...): compact is the reverse of extract, it compact the given variables into an associative array of key-value pairs.
    <?php
    $one = 'Monday';
    $two = 'Tuesday';
    $three = 'Wednesday';
    $dayArray = compact('one', 'two', 'three');
    var_dump($dayArray);
    ?>
    array (size=3)
      'one' => string 'Monday' (length=6)
      'two' => string 'Tuesday' (length=7)
      'three' => string 'Wednesday' (length=9)

Functions

A PHP function:

  1. receives arguments (or parameters) from the caller,
  2. performs operations defined in the function body, and
  3. returns a single piece of result to the caller.

The syntax is as follows:

<?php
function functionName(parameter, ...) {
   functionBody;
   return returnValue;
}
?>

Examples,

<?php
// Define a function called sayHello
function sayHello($name) {
   return "Hello, $name";
}
 
// Invoke the function sayHello
echo '<p>'.sayHello('Peter').'</p>';
$myName = 'Paul';
echo '<p>'.sayHello($myName).'</p>';
?>
Pass by Reference

In the above example, the parameters are passed into the function by value. That is, a clone copy is made and pass into the function. Changes within the function body will not be reflected in the original variable.

You can also pass the parameters into a function by reference. In this case, the address of the variable is passed into the function. Change to the value within the function will be reflected in the variable. To pass parameters into functions by reference, append a & sign to the variable. For example,

// $v2 passed by reference
function funByRef($v1, &$v2) {
  $v1 = $v1 * 2;
  $v2 = $v2 * 2;
  var_dump($v1); // int(6)
  var_dump($v2); // int(10)
}

$a = 3;
$b = 5;
funByRef($a, $b);
var_dump($a);  // int(3)  - no change
var_dump($b);  // int(10) - change thru the function
Default Value for Trailing Arguments

Caller can omit trailing arguments, which can be set to some default values. For example,

// $v2 can be omitted and takes the default value
function funWithDefault($v1, $v2 = 8) {
  return $v1 + $v2;
}

$a = 3;
$b = 5;
var_dump(funWithDefault($a));     // int(11) - $v2 default
var_dump(funWithDefault($a, $b)); // int(8)
//var_dump(funWithDefault());     // error
Function Overloading

PHP does NOT support function overloading (unlike C++/Java). But you can set default trailing parameter values to simulate function overloading.

Commonly-used PHP Built-in Functions - Output
  • print: similar to echo. print and echo are actually language constructs instead of functions. Hence, there is no need for parentheses for their arguments.
  • printf(formatString, var, ...): similar to C's printf().
  • sprintf(formatString, var, ...): returns the formatting string, instead of sending it to the output.
Commonly-used PHP Built-in Functions - Date/Time
  • time(): returns the current timestamp in Unix-style, i.e., number of seconds since January 1, 1970.
  • mktime(hour, minute, second, month, day, year): returns a timestamp instance of the given date/time.
  • date(formatSpecifier): format and print the current time (as returned by time()).
  • date(formatSpecifier, timeStamp): format and print the given timeStamp.
  • date_default_timezone_set(timeZoneIdentifier): set the default time zone for all the time and date functions, default is UTC (or GMT).

For example,

<?php
// default time zone is GMT (or UTC)
echo date('Y-m-d h:i:s a') . '<br>';
   // Year:   Y (yyyy), y (yy)
   // Month:  m (01-12) M (Jan-Dec)
   // Day:    d (01-31) j(1-31) D (Mon-Sun)
   // Hour:   G (0-23) H(00-23) h(01-12) a (am/pm) A (AM/PM)
   // Minute: i (00-59)
   // Second: s (00-59)
 
echo date('r') . '<br>';
   // r: RFC2822 full date/time
   // c: ISO8601 full date/time
 
date_default_timezone_set('Asia/Singapore');
echo date('Y-m-d G:i:s') . '<br>';
echo date('r', time()) . '<br>';
?>

Many date manipulation functions are available, e.g., date_add(), date_sub(), date_diff(), etc. Check the PHP manual for details.

System Call

You can use exec() to do a system call.

// Syntax
exec(command, output, status);
 
// Example
exec(escapeshellcmd('dir'), $output, $status);

[TODO]

Scope of Variables

Page's Global Variable (with Page-Scope)

The scope of variables is within the page that they are defined. They are available to the included and required files. On the other hand, the variables defined in the included and required files are also available immediately after the include an require. In other words, the include and require file are treated as part of the page.

The variable is not available to other pages. PHP calls the scope of these variables global. It is more appropriate to be called page-scope.

HTTP is a state-less protocol. To pass a variable from a page to another page requires proper session management.

Function's Local Variables

A variable defined within a function is a local variable of the function, and it is not visible outside the function.

Keyword global

Inside a function, to access a variable defined outside the function, you need to use the keyword global. For example,

<?php
$count = 0;
 
// Define a function containing static variable
function countUp() {
   global $count;
   $count++;
   return $count;
}
 
// Invoke the function multiple times
echo countUp().' '.countUp().' '.countUp().' ';
?>

Take note that the keyword global does not make the variable a global variable! This is really a bad choice of keyword!

$GLOBALS Associative Array

PHP stores all the page-scope global variables in a the $GLOBALS associative array.

Hence, within a function, instead of using global keyword, you can also access variable defined outside the function via the $GLOBALS associative array. For example,

<?php
$count = 0;   // Store in $GLOBALS['count']
 
function countUp() {
   ++$GLOBALS['count'];
   return $GLOBALS['count'];
}
 
// Invoke the function multiple times
echo countUp().' '.countUp().' '.countUp().' ';
?>
Keyword static

Within a function, you can declare a variable static. That variable retains its value across multiple invocations. For example,

<?php
// Define a function containing static variable
function countUp() {
   // This statement is run only for the first invocation and skipped for "subsequent" invocations
   static $count = 0;
   $count++;
   return $count;
}
 
// Invoke the function multiple times
echo countUp().' '.countUp().' '.countUp().' ';
?>
Superglobal Variables

As mentioned, in PHP, global variables refers to the page-scope variables within a page. PHP pre-defines some variables, which is available in all pages, called superglobal variables. They are associative array:

  • $_GET: an associative array of GET request key-value pairs.
  • $_POST: an associative array of POST request key-value pairs.
  • $_COOKIE: an associative array of key-value pairs in the request cookie.
  • $_REQUEST: contains GET, POST and COOKIE data from the request message
  • $_SERVER: server information, such as $_SERVER['PHP_SELF'] shows the filename of the current page.
  • $_SESSION: for session management
  • $_FILES: uploaded file
  • $_ENV: environment variables
  • $GLOBALS: maintains all page-scope global variable, accessible within functions.

You can do a var_dump() to view the contents of these superglobals, e.g., var_dump($GLOBALS).

File Handling

file_exists(filename): returns TRUE if the given file exists.

<?php
file_exists('out.txt') ? echo 'File exits' : echo 'File does not exist';
 
$fh = fopen('out.txt', 'w') or die('Cannot open file');
$outText = <<<_END
Testing Line 1
Testing Line 2
Testing Line 3
_END;
fwrite($fh, $outText) or die('Cannot write to file');
fwrite($fh, 'Done') or die('Cannot write to file');
fclose($fh);
echo 'Write Done!';
 
$fh = fopen('out.txt', 'r') or die('Cannot open file');
$inText = fgets($fh);     // read one line
echo $inText;
$inText = fread($fh, 3);  // read 3 lines
echo $inText;
fclose($fh);
echo 'Read Done!';
?>
  • r: read from the beginning of the file.
  • r+: read from the beginning of the file and allow write.
  • w: truncate the file and write from the beginning of the file.
  • w+: truncate the file and write from the beginning of the file, allow read.
  • a: append, write to the end of the file.
  • a+: append with read. write to the end of the file.

copy(inFile, outFile):

rename(oldFile, newFile):

unlink(filename): delete file

mkdir(): make directory

REFERENCES & RESOURCES

  1. PHP mother site @ http://www.php.net; "PHP Manual" @ http://php.net/manual/en/index.php; "PHP Language Reference" @ http://www.php.net/manual/en/langref.php.