PHP in 1 Hour
Example here are based on PHP version 5.x. For installation, see PHP Install .
Code Markers, Comment Syntax
PHP code must be enclosed between delimiters like this
<?php code ?>
Anything outside of it is printed as is.
<?php # this is comment. (bash style) // comment too, start with 2 slashes. (C style) 5 + 4; /* Java, C++ style, multi-line comment is also supported. */ ?> hi there
Save the above as myfile.php
. You can run it in the command line like this: php myfile.php
, or, you can run it in browser thru http server. The result output is: “hi there”.
Omit Ending Tag
The ending ?>
can be omitted if nothing comes after it. It is recommended to omit ending tag.
print version
<?php echo phpversion(); # 5.3.10-1ubuntu3.16 ## print hundreds lines of config info phpinfo();
[see PHP Version History]
Strings
Quoting String
use single quote for literal string.
<?php # single quoted string's content is literal. # The \n will be printed as blackslash and n echo 'hi there\n something';
use double quote for interpreted string. That is, use \n
for line break, and $var_name
for variable value.
<?php $x = 4; /* double quoted strings are interpreted. \n is a new line. Variable become values */ echo "I have $x apples\n"; // prints “I have 4 apples” with a newline
<?php // string can contain Unicode characters, or literal line break echo "α β and ♥";
If you are using Unicode, your HTML should declare Unicode encoding. See: Character Sets and Encoding in HTML .
String Operations
join string
<?php // use period to join string echo "Once " . "upon a time";
substring
<?php // substring, use substr( $myStr, $startIndex, $length). Index starts with 0 $aa = "012345"; echo substr($aa, 0, 4); // prints “0123”
string length
<?php // string length $aa = "once"; echo strlen($aa); // prints 4
Global and Local variables
Variables do not need to be declared. All variables must have a dollar sign $
in front. Variable always have a dollar sign in front.
(Unlike perl, the dollar sign (aka “sigil”) does not change depending on the value of the variable. In PHP, there is no perl's concept of “context”.)
<?php $xx = 4; echo "value of xx is $xx";
Basically all variables are global. Variables inside functions definition are local to that function.
<?php $x = 4; function xx() { echo "value of x is $x"; # x here is null } xx(); # prints: "value of x is "
To refer to global vars inside function definition, declare it first by putting global
in front of the var.
<?php $x = 4; function xx() { global $x; echo "→ $x"; } xx(); # prints → 4
Using a curly brace block {…}
does NOT make variables inside it local.
True and False
true
and false
are built-in boolean type. Case does not matter. true
is the same as True
.
The following are all FALSE:
- the integer
0
(zero) - the float
0.0
(zero) - the empty string
""
, and the string"0"
- array with zero elements
- object with zero member variables (PHP 4 only)
- the special type
NULL
(including unset variables) - SimpleXML objects created from empty tags
Example:
<?php $x = 4; if ($x == 4) {echo "yay";} else {echo "nay";} # yay if (true) {echo "yay";} else {echo "nay";} # yay if (trUe) {echo "yay";} else {echo "nay";} # yay
If Then Else
simple if.
<?php $x = 4; if ($x <= 4) {echo "yay!";}
if else.
<?php $x = 4; $y = 5; if ($x == $y) {echo "yay";} else {echo "nay";}
else if.
<?php $a=3; $b=4; if ($a > $b) { echo "case 1"; } elseif ($a == $b) { echo "case 2"; } else { echo "case 3!"; }
Loop, Iterations
while loop.
<?php $i = 1; while ($i < 5) { echo "$i\n"; $i++; }
for loop.
<?php for ($i = 1; $i < 5; $i++) { echo $i; }
Keyword “break” can be used to exit a loop. Example:
<?php for ($i = 1; $i < 8; $i++) { echo $i; if ($i == 4) {break;} }
Lists (Array)
PHP combines the concepts of “array/list” and “hash/keyed-list” into one. It is just called “array”.
A PHP array is just a sequence of things. Each element is actually a pair, made of a “key” and a “value”. The “key” can be omitted if you don't need a list of pairs. If a key is omitted, they are automatically generated using incremental indexes starting from 0.
Here are examples of manipulating array as simple list without using the “key”.
Array is created using array()
. Example:
<?php $x = array(7,2,3,"yes",5); print_r($x); /* prints: Array ( [0] => 7 [1] => 2 [2] => 3 [3] => yes [4] => 5 ) */
print_r
is for printing array or other variable in a human-readable way.
Array as Pairs/Hash/Keyed-List
For using array as a keyed-list (aka hash-table, dictionary, associative list), see PHP: Hash Table Tutorial .
Length
Use count()
to get the number of elements.
<?php $x = array(7,"yes",5); echo count($x); // prints 3
Getting a Element
Extracting element can be done like this $array[key]
.
<?php $x = array(7, 2, 3, "yes", 5); echo $x[1]; // prints 2
Replacing a Element
<?php $x = array(7, "yes", 5); $x[1] = "no"; echo $x[1]; // prints no
Appending a Element
Adding a element is done like this $myArray[new_key] = new_value
. The new_key must be a key that does not exist already, otherwise it simply replace that key's value.
If you are using array as simple list without keys, and have never removed any element in your list, you can add new ones with automatic index like this: $myList[] = new_value
.
<?php $x = array("uni", "bi", "tri"); $x[] = "quad"; // appending a element print_r($x); /* Array ( [0] => uni [1] => bi [2] => tri [3] => quad ) */
Removing Elements
To delete a element, use unset()
.
<?php $x = array(7, "yes", 5); unset($x[1]); // removes the "yes" print_r($x); // element with index 1 no longer exist. /* output Array ( [0] => 7 [2] => 5 ) */
WARNING: Once a element is deleted, there no longer exist a element with that element's index. In other words, the array is not “re-indexed”, and in fact there is no such concept as “re-indexing”. If you want the index to be sequential starting from 0 again, just create a copy like this: $newA = array_values($oldA);
.
Nested List
Arrays can be nested.
<?php $x = array(7, "yes", 5); $y = array("woot", $x, "wee"); print_r($y); /* output Array ( [0] => woot [1] => Array ( [0] => 7 [1] => yes [2] => 5 ) [2] => wee ) */
To get a element from a nested array, use the form $myArray[key1][key2][…]…
. Example:
<?php $x = array(7,"yes",5); $y = array("woot", $x, "wee"); echo $y[1][0]; // prints 7
Keyed-List
A keyed list (aka hash-table, dictionary, associative list) in PHP is simply called array. It is constructed like this array(key1 => val1, key2 => val2, …)
. Example:
<?php $x = array("mary" => 19, "joe" => 16); print_r($x); /* Array ( [mary] => 19 [joe] => 16 ) */
Get Values
To get value of a element, use the form $myArray[key]
.
<?php $x = array("mary" => 19, "joe" => 16); echo($x["mary"]); ?>
Note that the key should be quoted, when it is not a number.
Modify/Add A Entry
To add a entry, use the form $myArray[key] = val
. If the key exist, old value will be replaced. Otherwise, a new entry will be added.
<?php $x = array("mary" => 19, "joe" => 16); $x["mary"] = 18; // modify a entry $x["vicky"] = 21; // add a entry print_r($x);
Delete a Entry
To delete a entry, use unset()
.
<?php $x = array("mary" => 19, "joe" => 16); unset($x["mary"]); print_r($x);
Check Key Exists
To check if a key exists, use array_key_exists()
.
<?php $x = array("mary" => 19, "joe" => 19); echo array_key_exists("mary", $x);
Get Just Keys
To get just the keys, use array_keys()
.
<?php $x = array("mary" => 19, "joe" => 16); print_r(array_keys($x)); /* Array ( [0] => mary [1] => joe ) */
Get Just Values
To get just the values, use array_values()
. The function array_values()
effectively replaces all the keys by numerical indexes starting from 0.
<?php $x = array("mary" => 19, "joe" => 16); print_r(array_values($x)); /* Array ( [0] => 19 [1] => 16 ) */
Loop thru Values
To go thru a list, use foreach
. Here's a example of looping thru a list and accessing its values:
<?php $aa = array("uni", "bi", "tri"); foreach ($aa as $x) { echo "$x "; } // prints uni bi tri
Loop thru Keys and Values
Here's a example of looping thru a list and accessing both keys and values:
<?php $aa = array("uni", "bi", "tri"); foreach ($aa as $k => $v) { echo "$k,$v; "; } // prints 0,uni; 1,bi; 2,tri;
Map thru Values
Map a function to a array.
<?php function ff($n) {return($n+1);} $a = array(3,9,4); $b = array_map( ff, $a); // $b is (4,10,5) print_r($b);
Define a Function
A function is defined using keyword function
. Like this:
<?php /* ff($x,$y) returns x + y */ function ff($x,$y) { return($x+$y); } echo ff(3,4); // prints 7
Optional Parameters
<?php /* ff($x,$y) returns x + y. If $y is not given, default to 1. */ function ff($x,$y=1) { return($x+$y); } echo ff(3); // prints 4
Module
A collection of functions can be written and saved into a file. This file can then be loaded using require()
.
For example, save the following in a file and name it myPackage.php
.
<?php function ff($x) { return($x+1); }
Now, eval the following code:
<?php require("myPackage.php"); echo ff(3); // prints 4
require()
works as if the whole file's content is inserted in-place.
As of PHP 5.2.4 (), there is no namespace mechanism for importing functions or packages.