Introduction
PHP is a popular open-source 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 with a marketeer) 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:
- 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.
- HTML-embedded Server-side Scripts: The server-side script must be interpreted under a PHP-capable Web Server (such as Apache HTTP Server) to return an HTML page.
We shall focus on PHP Server-side scripts, 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 to return an HTML page. 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/MariaDB/PostgreSQL) to generate dynamic web pages.
Read "Setting Up Apache/MySQL/PHP (AMP) for Linux, Windows and macOS".
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/macOS) to create the following PHP script and save as "hello.php
" under your web server's document root directory (e.g, "htdocs
" for XAMPP, "www
" for WampServer):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!DOCTYPE html> <!-- hello.php --> <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 right-click and "View Page Source" to check the output received by the client:
<!DOCTYPE html>
<!-- hello.php -->
<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:
- PHP can be used as server-side script. The server processes the PHP script and returns its output.
- 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
// RunPhpinfo.php - Run phpinfo() builtin function
phpinfo();
?>
Run the script from a web browser via http://localhost/RunPhpinfo.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 22 |
<!DOCTYPE html> <!-- PrintTimeTable.php --> <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?
- 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. - You can use the
echo
statement to output a string. You can also use the C-likeprintf()
for formatted output. - 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 "HTMLFormTest.php
":
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<!DOCTYPE html> <!-- HTMLFormTest.php --> <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> <input type="submit" value="submit"> </form> </body> </html> |
How it works?
- An HTML form is defined (Lines 14-17) having a text field with a name called
username
(Line 15). This form uses POST method with defaultaction
to the current page. - In the PHP script (Lines 9-13), 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']
returns the value of the keyusername
. The built-in functionisset($_POST['username'])
returns TRUE, if the value of the given key is set. During the first visit to this page, the keyusername
is not set in the POST request parameters. Hence, the hello message is not displayed. Once user enters the name and submit the form to this page for processing,username
is set; and the hello message will be displayed. - In the
echo
command (Line 11), the dot (.
) operator concatenates two strings; the built-in functionhtmlentities(str)
(orhtmlspecialchars(str)
) converts all the special characters to HTML entities (e.g.,>
to>
,<
to<
,"
to"
,&
to&
). 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). - Try "View Page 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 (which is not popular).
Running PHP Scripts From Command-line
For example, prepare the following PHP script and save as "helloCLI.php
" in a directory of your choice:
<?php
// helloCLI.php
echo "hello, world!\n";
?>
To run the PHP Script:
$ cd /path/to/helloCLI.php $ php helloCLI.php hello, world!
The php
(or php.exe
in Windows) interpreter shall be accessible via the PATH. Alternatively, you could provide the full-path to the php interpreter (e.g., <XAMPP_HOME>\php\php
).
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 // PrintTimeTable.php $size = readline('Enter the size of table: '); // prompt and read input for ($row = 1; $row <= $size; ++$row) { for ($col = 1; $col <= $size; ++$col) { printf('%3d', $row * $col); } echo "\n"; } ?> |
Take note that readline()
is only applicable for standalone program. For server-side script, you need to use an HTML form to get the user input.
Unix PHP (Standalone Executable) 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 (x
). For example, create the following file called "helloExe.php
":
#!/usr/bin/php
<?php
// helloExe.php
echo "hello, world!\n";
?>
// Set the file executable $ cd /path/to/helloExe.php $ 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 "Eclipse PDT (PHP Developer Tool)" and "xDebug".
[TODO] Other IDEs.
PHP Language Syntax
The official "PHP Language Reference" is available @ http://php.net/manual/en/langref.php.
PHP Versions
[TODO]
Basic object-oriented features was added in PHP 3, improved in PHP 4, and completely rewritten in PHP 5. PHP 6, 7, 8 ....
PHP vs JavaScript
PHP is typically used together with JavaScript (and HTML/CSS) in a webapp. Take note and remember that PHP syntax is quite different from JavaScript (which follows Java, and hence C/C++). For examples:
- in PHP, a variable name starts with a
'$'
sign; there is novar
keyword to declare a variable; - in PHP, an array is defined via
array('1', '2', '3')
(or['1', '2', '3']
in PHP 5.4) instead of{'1', '2', '3'}
; - in PHP, an associate array is defined via
array('name' => 'peter', 'age' => 18)
instead of{name:'peter', age:18}
; - and many more.
Basic Syntax
Comments
- A multi-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 your readers and you (3 days after writing the code). 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 (\t
) and newline (\n
)) are ignored. I strongly recommend that you use additional whitespaces to format your code, so that it can be understood by your readers and you.
Case Sensitivity
PHP is case sensitive.
Expressions
An expression is a combination of variables, literal values and operators, that can be evaluated to produce a value. For example: ($row + 99) * $col
.
Output via echo and print Language Constructs
You can use the echo
or print
to produce output. The signatures are:
echo (string ...$expressions) : void // accept a list of expressions print (string $expression) : int // 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
. They produce no additional newlines or spaces.
For examples,
<?php // echo_print_test.php echo 'Hello, world!<br>'; // echo one string echo('Hello, world!<br>'); // Parentheses are optional. echo PHP_EOL; // platform-dependent end-of-line (newline) //Hello, world!<br>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>'; echo PHP_EOL; //one two three<br>one two three<br> print 'Hello, world!<br>'; print('Hello, world!<br>'); // parentheses are optional print 'one' . ' ' . 'two' . ' ' . 'three' . '<br>'; // one string print PHP_EOL; //Hello, world!<br>Hello, world!<br>one two three<br> ?>
echo
and print
are not really functions, they are program constructs. Hence, the parentheses (for function's arguments) are optional. echo
does not have a return value. print
always return int 1.
echo shortcut <?= ?>
echo
also has a shortcut syntax in the form of <?=$expression ?>
, for example,
<?php
$message = "hello, world"
?>
<p><?=$message?></p>
The output is:
<p>hello, world</p>
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 tovar_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, $var1, ...)
: similar to C'sprintf()
.sprintf($formatString, $var1, ...)
: returns the formatting string, instead of sending it to the output.
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
There are four types of strings in PHP:
- single-quoted strings
- double-quoted strings
- heredoc
- nowdoc
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>"; ?>
<p>The count is 5.
</p><p>The count is $count.\n</p><p>The count is 5.</p><p>The count is 5.</p><p>The count is 5.</p>
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 parses 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>"; // Warning: Undefined 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()}"; //output is: 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
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 ?>
The output is:
<h1>This is a multiline string</h1>
<p>First Line</p>
<p>Hello, world</p>
<p>Take note that variables/Escape characters are expanded.</p>
<p>Last Line</p><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>
All the newlines and whitespaces are preserved within the quotes. Again, double-quoted string performs variable substitution; whereas single-quoted string does not.
Heredoc
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 = <<<_EOT <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> _EOT; 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-names _EOT
(end-of-text) or _END
, you can choose any tag-name such as END
, OUTPUT
, and etc. The tag name shall begin with a letter or underscore, and consists of letters, digits or underscore.
Nowdoc
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 = <<<'_EOT' <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> _EOT; 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 oflength
. - strtoupper(str), strtolower(str): return the uppercase/lowercase 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 (regex)
Regular Expression (regex) is a power tool and is essential in program development.
Built-in Regex 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:
- integer: platform-specific (such as 32-bit or 64-bit).
- double: also platform-specific (single-precision or double-precision).
- string: single-quoted, double-quoted, nowdoc, and heredoc.
- boolean: PHP supports native boolean type, which takes value of either
TRUE
orFALSE
. 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).
'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.) - integer
- object: an instance of a class.
- resource: represents external resources, such as image, file, database.
- array: array of the above types.
- 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()
.
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), PHP_EOL; //integer echo gettype($myDouble), PHP_EOL; //double echo gettype($myString), PHP_EOL; //string echo gettype($myBoolean), PHP_EOL; //boolean echo gettype($myArray), PHP_EOL; //array echo gettype($myNull), PHP_EOL; //NULL // is_xxx() echo is_integer($myInt), PHP_EOL; //1 (TRUE) echo is_string($myInt), PHP_EOL; //nothing (FALSE) // Type Casting echo gettype((string)$myDouble), PHP_EOL; //string echo gettype((double)'1.234'), PHP_EOL; //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 tovar_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); //int(5)(newline) echo '<br>', PHP_EOL; var_export($myInt); //5 echo '<br>', PHP_EOL; print_r($myInt); //5 echo '<br>', PHP_EOL; $myString = 'Hello'; var_dump($myString); //string(5) "Hello"(newline) echo '<br>', PHP_EOL; var_export($myString); //'Hello' echo '<br>', PHP_EOL; print_r($myString); //Hello echo '<br>', PHP_EOL; $myArray = array('Mon', 'Tue', 'Wed'); var_dump($myArray); //array(3) { // [0]=> // string(3) "Mon" // [1]=> // string(3) "Tue" // [2]=> // string(3) "Wed" //}(newline) echo '<br>', PHP_EOL; var_export($myArray); //array ( // 0 => 'Mon', // 1 => 'Tue', // 2 => 'Wed', //) echo '<br>', PHP_EOL; print_r($myArray); //Array //( // [0] => Mon // [1] => Tue // [2] => Wed //)(newline) echo '<br>', PHP_EOL; ?>
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:
intval($var)
: The functionintval($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.- Casting operator
(int)$var
: same asintval($var)
. settype($var, 'integer')
: convert$var
to integer type, and return either TRUE/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) ?>
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 ofinclude
. - require and require_once: The
require
is identical toinclude
, except that it handles errors differently. If an error occurs, theinclude
generates a warning, and continues executing the script. Therequire
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 PHP_EOL; // Use the foreach loop (missing indexes are skipped) foreach($a1 as $item) { echo "$item, "; } ?>
Take note that:
- The elements need not of the same type.
- The size is dynamically adjusted for new elements.
- 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.
- 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:
- receives arguments (or parameters) from the caller,
- performs operations defined in the function body, and
- 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
andecho
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
- 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.