PHP Basics – PHP Certification Exam Series [1]

PHP Basics ﹣ PHP Certification Exam

Introduction: This is the first part of my study notes for the Zend PHP Certification Exam. You can read more about my PHP Certification exam journey here.

PHP Tags

Standard Tags – best solution for portability and backwards compatibility, because they are guaranteed to be available and cannot be disabled by changing PHP’s configuration file.

... code

However there can be only one open tag in the begining of the page <?php .
Short Tags – can be disabled (often for XML compliance) with short_open_tag directive in php.ini:

... code

This virant of short tag is identical to <? echo, enabled even if short_open_tag is disabled:

<?=$variable ?>

Script tags is also guaranted access, same as standart tags:

<script language="php">
... code

ASP Tags – must be enabled specifically in the php.ini file via the asp_tags directive:

... code
<%=$variable; %>

If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag (e.g. header() needs to be at the very beginning of the output code).  The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The following is correct:

echo 'hello' // the ; is optional

PHP files do not need the ‘executable’ privilege.


The “one-line” comment styles only comment to the end of the line or the current block of PHP code (or \r, \n, \r\n), whichever comes first. This means that HTML code after // … ?> or # … ?> WILL be printed: ?> breaks out of PHP mode and returns to HTML mode, and // or # cannot influence that. If the asp_tags configuration directive is enabled, it behaves the same with // %> and # %>. However, the </script> tag doesn’t break out of PHP mode in a one-line comment.

// This is a single line comment

# This is also a single line comment
# New line comment ?> Here new line comment dont work, and this will be printed

Multi-line comments end at the first */ encountered. Make sure you don’t nest multi-line comments. It is easy to make this mistake if you are trying to comment out a large block of code.

This is a multi-line

/* this is also
commented */ but this don't */

Below you can find DocComment example. For PHP itself it looks like regular comment. For futher information you can visit phpDocumentor site.

* API Documentation Example
* @param string $bar
function foo($bar) { }


In PHP, almost anything you write is an expression (i.e. value, functions, etc.). The simplest yet most accurate way to define an expression is “anything that has a value”.

A statement has the form of ‘expr ;‘ that is, an expression followed by a semicolon. In ‘$b = $a = 5;’, ‘$a = 5’ is a valid expression, but it’s not a statement by itself. ‘$b = $a = 5;’ however is a valid statement.

Note: since assignments are parsed in a right to left order, you can also write ‘$b = $a = 5’.


An operator is something that takes one or more values (or expressions) and yields another value (so that the construction itself becomes an expression).
Operators can be grouped according to the number of values they take. Unary operators take only one value, for example ! (the logical not operator) or ++ (the increment operator). Binary operators take two values, such as the familiar arithmetical operators + (plus) and – (minus), and the majority of PHP operators fall into this category. Finally, there is a single ternary operator, ? :, which takes three values; this is usually referred to simply as “the ternary operator” (although it could perhaps more properly be called the conditional operator).
Operator Precedence and Associativity 
The precedence of an operator specifies how “tightly” it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication * operator has a higher precedence than the addition + operator. Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18.

When operators have equal precedence, their associativity decides whether they are evaluated starting from the right, or starting from the left. Operation’s associativity can either be left (operations are performed left-to-right), right (operations are performed right-to-left) or none (for operations that cannot be associated).

mostly left or non-associative except ! ++ — ~ (int) (float) @ = += -= *= /= .= %= &= |= ˆ= <<= >>= which are right

The statement 1 < 2 > 1, is illegal in PHP (same associativity and precedence), whereas, the statement 1 <= 1 == 1 is legal.

$a = 3 * 3 % 5;   // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2;   // (true ? 0 : true) ? 1 : 2 = 2

Arithmetic Operators

Works same for the real world:


echo 2 + 2; // Addition. Will print 4
echo 3 - 2; // Subtraction. will print 1
echo 1 * 2; // Multiplication. Will print 2
echo 4 / 2; // Division . Will print 2
echo -2; // Negation. Will print -2
echo 3 % -2 // Modulus. Will print 1
echo -3 % 2 // Modulus. Will print -1
echo 0x8A + 3 // Will print 141 (0x8A = 8x16 + 10 = 138), note always returns the decimal values


The division operator / returns a float value unless the two operands are integers (or strings that get converted to integers) and the numbers are evenly divisible, in which case an integer value will be returned. If try to division by zero then PHP Warning: Division by zero will be thrown.
Operands of modulus are converted to integers (by stripping the decimal part) before processing.
The result of the modulus operator % has the same sign as the dividend — that is, the result of $a % $b will have the same sign as $a. e.g. (5 % -3) = 2;  (-5 % 3) = -2

The dot operator:

$a = 1;
$a .= 2;
echo $a; // 12

Assignment Operators

The basic assignment operator is =. It means that the left operand gets set to the value of the expression on the right (that is, “gets set to”). The left side must be a variable.
The value of an assignment expression is the value assigned. That is, the value of $a in expression $a = 3 equal to 3. e.g. $a = ($b = 4) + 5; // value of $a is 9
For arrays, assigning a value to a named key is performed using the => operator. The precedence of this operator is the same as other assignment operators.
In addition to the basic assignment operator, there are “combined operators” for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example:

$a = 3;
$a += 5; // Equal 8
3 = $a; // output error

Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other.

Assignment by Reference

Assignment by reference is also supported, using the $var = &$othervar; syntax (ampersand & before variable). Assignment by reference means that both variables end up pointing at the same data, and nothing is copied anywhere. Once assigned, by reference will continue in effect until unset. By reference is slower in PHP.

$a = 3;
$b = &$a; // or a space in-between & $a // $b is a reference to $a
$b = 50;print "$a\n"; // prints 50
print "$b\n"; // prints 50

As of PHP 5, the new operator (for objects) assigns by reference automatically, so assigning the result of new by reference (e.g. $a = &new C;) results in an E_DEPRECATED message in PHP 5.3 and later.

Bitwise Operators

Bitwise operators allow evaluation and manipulation of specific bits within an integer. Integral numbers are internally converted into bits: 5 -> 0101 = 0*8 + 1*4 + 0*2 + 1*1
Use parentheses to ensure the desired precedence. For example, $a & $b == true evaluates the equivalency then the bitwise and; while ($a & $b) == true evaluates the bitwise and then the equivalency.
Be aware of data type conversions. If both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters’ ASCII values.

  • $a & $b (And) — Bits that are set in both $a and $b are set. Matching 1 in both (e.g. 4&1 // result 0).
  • $a | $b (Or (inclusive or)) — Bits that are set in either $a or $b are set. At least one 1 (e.g. 4|1 // result 5).
  • $a ^ $b (Xor (exclusive or)) — Bits that are set in $a or $b but not both are set. Only one 1 in both.
  • ~ $a (Not) — Bits that are set in $a are not set, and vice versa. Convert 0 in to 1 and 1 in to 0
  • >> (Shift Right) – All of the bits in the binary number shift N places to the right in the number, the right most digit(s) falls out, and the resulting number is padded on the left with 0s. A right shift of one is equivalent to dividing a number by two, and tossing the remainder (e.g. 4>>1 // result 2).
  • << (Shift Left) – All of the digits shift N places to the left, padding the right with 0s. A left shift of one is equivalent to multiplying a number by two  (e.g. 4<<1 // result 8).
  • Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit (the sign bit is the left most bit indicating where the signed integer is positive(0) or negative(1)) is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved.

An example of bitwise operation is the PHP error reporting feature. e.g. E_ALL & ~E_NOITCE (00000000000000000111011111111111 & 11111111111111111111111111110111 yields 00000000000000000111011111110111 the number of digits depends on the platform, the above is on a 32-bit platform)

Comparison Operators

Comparison operators, as their name implies, allow you to compare two values.

$a == $b (Equivalence) — TRUE if $a is equal to $b after type juggling.
$a === $b (Identity) — TRUE if $a is equal to $b, and they are of the same type.
$a != $b $a <> $b (Non-equivalent) — TRUE if $a is not equal to $b after type juggling.
$a !== $b (Non-identical) — TRUE if $a is not equal to $b, or they are not of the same type
$a < $b (Less than) — TRUE if $a is strictly less than $b.
$a > $b (Greater than) — TRUE if $a is strictly greater than $b.
$a <= $b (Less than or equal to) — TRUE if $a is less than or equal to $b.
$a >= $b (Greater than or equal to) — TRUE if $a is greater than or equal to $b.

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.
For various types, comparison is done according to the following:

  • null to string — Convert NULL to ””, or other words to empty string
  • bool or null to anything — Convert to bool
  • object to object — When using the comparison operator ==, object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class. On the other hand, when using the identity operator ===, object variables are identical if and only if they refer to the same instance of the same class
  • string, resource or number to string, resource or number — Translate strings and resources to numbers
  • array to array — Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise – compare value by value
  • array to anything — array is always greater
  • object to anything — object is always greater.

NOTE: ( 0 == “a” ) is true, (“1” == “01”) is true

Ternary Operator

Another conditional operator is the ?: (or ternary) operator. The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE. Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
Please note that the ternary operator is a statement, and that it doesn’t evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

It is recommended that you avoid “stacking” ternary expressions. PHP’s behaviour when using more than one ternary operator within a single statement is non-obvious.

print 0=='a1'? 'TRUE': 'FALSE'; or
0=='a1'? print 'TRUE': print 'FALSE';
but NOT 0=='a1'? echo 'TRUE': echo 'FALSE';

Error Control Operators

for suppressing errors (@). If the track_errors feature is enabled, any error message generated by the expression will be saved in the variable $php_errormsg.

Execution (backtick) Operators

“(backticks) – Execute the contents as a shell command (shortcut for shell_exec( )) with the same permissions as the web server. The backtick operator is disabled when safe mode is enabled or shell_exec() is disabled.

Incrementing/Decrementing Operators

for incrementing (++) and decrementing (–) numerical values for a variable (return error if operated on a value). If operate on a character value, it would increase or decrease the ASCII value by 1. Incrementing or decrementing booleans has no effect.

$a = 3;
echo $a++; // 3
$b = 3;
echo ++$b; // 4
Logical Operators
for performing logical operations on Boolean values (!, &&, ||, XOR)

NOTE: “||”,”&&” has a greater precedence than “or”,”and”.
$e = false || true; // $e gives true     $e = false or true; // gives true, same as ($e=false) or true;

for the and operator, if the expression on the left hand side evaluates to FALSE, FALSE will be returned immediately with further evaluating the right-hand expression, thus if(isset($A)&&$A==2){ } will NOT throw error is $A is not defined before.

String Operators

for joining two or more strings (.)

$a = 'Hello'; $b = ' World';
echo $a.$b; // Hello World 

Array Operators

$a + $b Union Union of $a and $b.
$a == $b Equality TRUE if $a and $b have the same key/value pairs.
$a === $b Identity TRUE if $a and $b have the same key/value pairs in the same order and of the same types (e.g. “0” and 0 are not the same type).
$a != $b Inequality TRUE if $a is not equal to $b.
$a <> $b Inequality TRUE if $a is not equal to $b.
$a !== $b Non-identity TRUE if $a is not identical to $b.

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

Type Operators

Instanceof – Returns true if the indicated variable is an instance of the designated class, one of it’s subclasses or a designated interface. Returns false if the variable is not an object. Gives fatal error if a constant is tested.

if ($obj instanceof A)

is_a( object, class_name ) is another function to check if the object is of this class or has this class as one of its parents. NOT deprecated from PHP 5.3

Types and Variables


  • Can only contain letters, numbers or underscores
  • Must start with a letter or an underscore ($this is not allowed)
  • Variable names are case-sensitive (while function names are case-insensitive)


  • Scalar types: boolean, string, integer, float.
  • Compound types: array, object.
  • Special Types: resource, null

Special Notes

  • to check for type of $a, use var_dump($a), gettype($a) or is_string($a)
  • (int),(integer),(bool),(boolean), etc. or settype($a,”bool”)
  • (string)$a or strval($a) or $object->_toSring to convert to string, note (string)TRUE = “1”, (string)FALSE = “”
  • unset($a) or (unset)$a cast to NULL
  • Complex syntax: {$name} or ${name}  // note: { $name} is not complex syntax
  • echo “This works: {$arr[‘key’]}“;  // the only way to use array with key within double quoted syntax
  • always assigned by value, except with the use of $new_variable = &$old_variable (pass by reference for named variable only, functions cannot be passed by reference)

String to Number Conversion

$foo = "10.0 pigs " + 1; // $foo is float(11)
$foo = "pigs 10" + 1; // $foo is integer (1)


Strings in PHP are collections of binary data like files, graphics, texts, etc. String can be as large as 2GB.

Each character is usually represented by a single byte in PHP. Strings in a PHP file is encoded in the encoding method of the script file. PHP has no native support for processing multi-byte character sets (like Unicode), extensions like mbstring must be installed to process multibyte characters properly.

Some functions doesn’t work with multibyte strings like substr() or strlen(). Others work with the current locale (setlocale()) like ucfirst(), strtoupper(). Some are dedicated functions for specific encoding e.g. utf8_encode(), utf8_decode().

Can be quoted in one of 4 ways:

  • ‘some text’ – characters within single quotes will be recorded as is, without variable or escape sequences interpreted and replaced (i.e. \n \r will NOT be interpreted)
  • “some text” – variables and escape sequences will be interpreted and replaced
  • <<< – Heredoc functions in a similar manner to double quotes, but is designed to span multiple lines, and allow for the use of quotes without escaping. As of PHP 5.3.0, it’s possible to initialize static variables and class properties/constants using the Heredoc syntax. Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be enclosed in double quotes.
  • Nowdoc – From PHP 5.3.0, nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc.
$greeting = <<<"GREETING" // heredoc $name is parsed
She said "That is $name's" dog!
$greeting = <<<'GREETING' // nowdoc $name is NOT parsed
She said "That is $name's" dog!


Can be specified in decimal (base 10), hexadecimal (base 16, precede with a 0x), or octal (base 8, precede with a 0) notation and optionally preceded by a sign (+, -)
To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary notation precede the number with 0b.

The maximum size of an integer is platform dependent, a maximum of ~2Billion is common.

Note: var_dump(01090); // 010 octal = 8 decimal as 9 is NOT present in octal notation

Float (aka Double)

1.234, 1.2e3, 7E-10 (E and e are the same)
The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value

Because of the way floats are represented internally, you should not test two floats for equality. [floor((0.1+0.7)*10) will usually return 7]
1.2e3 is float (evaluates to 1.2 x 10 x 10 x10)


  • Any integer other than 0 is cast to TRUE
  • Any string that is not empty or 0 is cast to TRUE (e.g. 000 is TRUE)
  • TRUE & FALSE are case-insensitive, though the all caps representation is common


Arrays can contain any combination of other variable types, even arrays or objects. Array elements are ordered.

For the keys, key casts will occur: floats will be cast to integers, bools to 1 (TRUE) or 0 (FALSE), NULL to “” (empty).

Enumerated array (keys are integers) and associative arrays (keys with strings).

When the key is not specified, PHP will automatically assign the key as an integer which is 1 larger than the largest integer key in the array formerly set (even if the key is destroyed earlier).

$array[‘key’] or $arrray{‘key’} are both correct. The key needs to be quoted, otherwise PHP will think it is a constant. If not a constant found, it is assumed to be quoted with a E_NOTICE thrown.

This will not work (parse error): print "Hello $arr['fruit']";
// change to "Hello ".$arr['fruit']; or "Hello {$arr['fruit']}";

$myArray = array (‘a’=>’aa’,’b’=>’bb’); is the same as
$myArray[‘a’]=’aa’; $myArray[‘b’]=’bb’;

use unset($myArray[‘key’]) or unset($myArray) to unset array


Objects allow data and methods to be combined into one cohesive structure. The new statement is used to instantiate an object from a class.

If an array is cast into an object, the elements will become properties of the object named with the keys. For any other value, the property ‘scalar‘ will contain the value.

$obj = (object)'name';
echo $obj->scalar;  // outputs 'name'


Special variable that represents some sort of operating system resource, generally an open file or database connection.
While variables of the type resource can be printed out, their only sensible use is with the functions designed to work with them. get_resource_type() can be used to return the type or resources, e.g. mysql link, file, etc.

Resources are freed by garbage collector when not used any more, with the exception of persistent database connection.

Callbacks (callable type hint)

Some functions accept another function (callback) as one of its parameters, e.g. call_user_func(), usort() or in a closure (an unnamed function).

function increment(&$var){ // call_user_func() not passed by reference
$a = 0;
call_user_func('increment', $a);
echo $a; // output 1


  • variables assigned NULL or defined without a value or unset()
  • can be checked by is_null() function
  • it has no value and no type
  • is not the same as the integer zero or an zero length string (which would have types)

Variable Variables

Variable variables cannot be used for superglobals ($_GET[‘name’], etc.)

$a = 'name';
$$a = "Paul";
echo ${'name'}; //Paul

Variable Functions

function myfunc() { … } // $a = function a(){} is invalid
$f = 'myfunc';
$f(); //will call myfunc();      


  • Variable variables cannot be used for superglobals
  • $_SERVER contains the header, path, file info, e.g. address, document root, http_host, http_user_agent, server_name, script_name, e.g. $_SERVER[‘SCRIPT_NAME’] // capital letters
  • $_ENV contains variables imported into PHP’s global namespace from the environment under which the PHP parser is running
  • $_REQUEST[‘name’] includes $_GET[‘name’], $_POST[‘name’] and $_COOKIE[‘name’], depending on the variables_order directive, $_GET is urldecode() automatically.
  • $_FILES contains the info of items uploaded through POST.
  • Dots and spaces in variable names are converted to underscores. For example <input name=”a.b” /> becomes $_REQUEST[“a_b”].
  • When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
  • <input type=”image” src=”image.gif” name=”sub” />
  • When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image.
  • Cookies are part of the HTTP header, so the setcookie() function must be called before any output is sent to the browser. Cookie data is then available in the appropriate cookie data arrays, such as $_COOKIE
  • $HTTP_RAW_POST_DATA contains the raw POST data, not available with enctype=”multipart/form-data”
  • $http_response_header array is similar to the get_headers($url) function, used together with file_get_contents($url)
  • When running from the command line, $argc will return the number of arguments passed to php (the filename is counted 1), $argv returns an array of the arguments.


In PHP, variables exist in the scope (i.e. global, function, class) where it is defined. Inside a function, global variables must be declared global if they are going to be used in that function.

function SUM() { global $a, $b; return $a + $b; }
function SUM() { return $GLOBALS['a'] + $GLOBALS['b']; }

Static declaration can be used to remember the last value of a variable inside a function/class when the function is called without the need to make the variable global.

function SUM($b) { static $a = 0; $a = $a + $b; return $a; } // each time the function is called, the value of $a will be altered and remembered for the next call

isset( )

True if the variable is defined and with a value other than NULL.


$result = $pdo->query("SELECT id, name, salary FROM employees");
while (list($id$name$salary) = $result->fetch(PDO::FETCH_NUM)) {…}


  • Only scalar values, cannot be changed or unsetted once set.
  • By convention, constant identifiers are always uppercase.
  • Follow the naming rules of PHP.
  • Have a global scope.
  • use get_defined_constants() to get a list of all constants.
  • use defined(Constant) to check whether the constant is defined.
  • If a constant is not defined, calling it will result in E_NOTICE
  • case-sensitive by default
define('ERROR', 'Something went wrong.',TRUE/FALSE); or (from PHP 5.3, only in top-level scope, i.e. not within function, etc.) const ERROR = 'Something went wrong.';
echo ERROR; or echo constant('ERROR'); // 'Something went wrong.' constant(ERROR) is WRONG echo error will be valid if TRUE is indicated in the 3rd argument which indicates case-sensitivity

End of Line Constant

To output the end of line character according to the OS


Magic __XXX__ Constants

PHP CORE provides a set of predefined constants (e.g. E_ERROR; TRUE; FALSE; NaN (not a number)). Some of which may change depending on where they are used. These magic constants are case-insensitive.

__LINE__ The current line number of the file.
__FILE__ The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
__DIR__ The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. (Added in PHP 5.3.0.)
__FUNCTION__ The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
__CLASS__ The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__ The trait name. (Added in PHP 5.4.0) As of PHP 5.4 this constant returns the trait as it was declared (case-sensitive). The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__ The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
__NAMESPACE__ The name of the current namespace (case-sensitive). This constant is defined in compile-time (Added in PHP 5.3.0).

Control Structures and Language Constructs

Elements that are built-into the language. A language construct is a syntactically allowable part of a program that may be formed from one or more lexical tokens in accordance with the rules of a programming language. The term Language Constructs is often used as a synonym for control structure which is NOT a function.



if ():
elseif: // must use elseif, else if can only be used in if(){ }else if(){ }


$expr ? true : false


Switch does loose comparison (==) rather than ===.

switch ($i) {
case 0: // a semi-colon may be used i.e. case 0;
     case 1:
     case 2:
echo "i is less than 3 but not negative";
case 3:
echo "i is 3";

switch ($i): // the alternative syntax
case 0:
echo “i equals 0”;
do { … break; … } while (0);  // a different usage of the do-while loop, to allow stopping execution in the middle of code blocks, by encapsulating them with do-while (0), and using the break statement.
note that the 3 expressions of the for loop can be empty or contains multiple expressions
$i = 1;
for ( ; ; ) {
if ($i > 10) {break;}
echo $i++;
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);

To speed up processing, the following is advisable for array operations:

for($i = 0, $size = count($people); $i < $size; ++$i) {
$people[$i]['salt'] = mt_rand(000000, 999999);


works only on arrays and objects; the internal pointer of the array is reset automatically on first executing

foreach ($array as $key=>$value){…} or foreach ($array as $value){…}

$arr = array(“one”, “two”, “three”);
The following are functionally identical:
while (list($key, $value) = each($arr)) {
echo “Key: $key; Value: $value<br />\n”;

foreach ($arr as $key => $value) {
echo “Key: $key; Value: $value<br />\n”;


Break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

break 0; is invalid. break; is identical to break 1;

continue is used within looping structures to skip the rest of the current loop iteration and begin the next iteration if present. a semicolon must be put after continue for clarity, i.e. continue; or continue 3;


The declare construct is used to set execution directives for a block of code. Only two directives are recognized: the ticks directive and the encoding directive (added in PHP 5.3). A tick is a special event that occurs internally in PHP each time it has executed a certain number of statements (tick is removed in PHP 6).

declare(ticks=1) {
// entire script here
// code here

The encoding declare value is ignored in PHP 5.3 unless php is compiled with –enable-zend-multibyte


Return statement immediately ends execution of the current function immediately, and returns its argument as the value of the function call. return will also end the execution of an eval() statement or script file.

It is common to leave the parentheses out, and you actually should do so as PHP has less work to do in this case.

return $a; // return the variable $a by reference
return ($a); // same as previous one


  • failure to find the file will produce a fatal E_COMPILE_ERROR level error
  • use the path given or specified in include_path
  • the code it contains inherits the variable scope of the line on which the include occurs, if included from a function, it has the scope of the function (not global)
  • all functions and classes defined in the included file have the global scope
  • parse as html if the PHP tag (<?php) are not present
  • will return 1 or FALSE (successful/unsuccessful) unless a return statement is in the require/include file.
  • if a function is declared in the require file, require more than once will give a PHP fatal error
  • may use the auto_prepend_file and auto_append_file configuration options in php.ini
  • $a = require ‘foo.php’; // parentheses not necessary


  • same as require/require_once
  • failure to find the file will produce a fatal E_WARNING level error

goto (from PHP 5.3)

The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label.

The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one (otherwise fatal error would result). You may jump out of switches or loops, and a common use is to use a goto in place of a multi-level break.

for($i=0,$j=50; $i<100; $i++) {
while($j--) {
if($j==17) goto end;
echo "i = $i";
echo 'j hit 17';

Output Language Constructs

echo '123'; // nothing is returned, a language construct
print 'something'; or print ('something'); // 'something' is printed and 1 is returned, a function
die; die(); or exit; exit();
return; // halt the execution and return a value, code after which will NOT run but parsed
__halt_compiler(); // useful for debugging, code after which will not be parsed 
Evaluation Language Constructs
empty(); // check whether a variable is emptyeval(); // run as PHP codeinclude/require(); or include_once/require_once();

reset(); // The reset() function is used to rewind the pointer to the beginning of an array.

Error Reporting

By default, PHP reports any errors it encounters to the script’s output. Unless you happen to be in a debugging environment, this is rarely a feature that you will want to take advantage of. Several configuration directives in the php.ini file allow you to fine-tune how—and which—errors are reported. The most important ones are error_reporting, display_errors (on|off) and log_errors (on|off).

It is not uncommon for a php developer to use show_source(), highlight_string(), or highlight_file() as a debugging measure.
error_reporting = E_ALL & ~E_NOTICE // in php.ini
error_reporting( E_ALL ^ E_NOTICE ); or ini_set(‘error_reporting’,E_ALL ^ E_NOTICE); // in php script
error_reporting( 0 ); // turn OFF error reporting, in php script

Set Error Handler

Your scripts can declare a catch-all function that is called by PHP when an error condition occurs by calling the
set_error_handler() function.

The function name of the old error handler (if any) is returned by the call to set_error_handler()—this allows you to stack several error handlers on top of each other, thus making it possible to have different functions handle different kinds of errors.
It’s important to keep in mind that your error handlerwill completely bypass PHP’s error mechanism—meaning that you will be responsible for handling all errors, and stopping the script’s execution if necessary.

Internal PHP functions uses error reporting while object oriented extensions use exceptions (see below).

$oldErrorHandler = set_error_handler ($myErrorHandler);


An exception can be thrown, and caught (“catched”) within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch block.

If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception …” message, unless a handler has been defined with set_exception_handler().

The Exception class may be extended to specific purposes. Use set_exception_handler($handler); to set a catch-all exception handler. Execution will stop after the exception_handler is called. restore_exception_handler() to restore the previous exception handler.

try {    } catch (Exception $e) { echo $e->getMessage(); }

Solves two problems:

  • Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  • Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.

Only four types of code units are affected by namespaces:

  • classes
  • interfaces
  • functions
  • constants.

A file containing a namespace must declare the namespace at the top of the file before any other code – with one exception: the declare keyword. Nested namespace is not allowed while multiple namespaces may be declared in the same file using the syntax:

namespace A { … }  namespace B { … }  namespace { … } // global scope

The same namespace may be defined in multiple files. Namespace name can be defined with sub-levels.
A class name can be referred to in three ways:

  1. Unqualified name, or an unprefixed class name like $a = new foo(); or foo::staticmethod();. If the current namespace is currentnamespace, this resolves to currentnamespace\foo. If the code is global, non-namespaced code, this resolves to foo. One caveat: unqualified names for functions and constants will resolve to global functions and constants if the namespaced function or constant is not defined.
  2. Qualified name, or a prefixed class name like $a = new subnamespace\foo(); or subnamespace\foo::staticmethod();. If the current namespace is currentnamespace, this resolves to currentnamespace\subnamespace\foo. If the code is global, non-namespaced code, this resolves to subnamespace\foo.
  3. Fully qualified name, or a prefixed name with global prefix operator like $a = new \currentnamespace\foo(); or \currentnamespace\foo::staticmethod();. This always resolves to the literal name specified in the code, currentnamespace\foo. To reference the global function, \strlen($string) can be used.

The value of __NAMESPACE__ is a string that contains the current namespace name. In global, un-namespaced code, it contains an empty string. The namespace keyword is used to request explicitly an element from the current namespace or sub-namespace.

Two kinds of aliasing or importing: aliasing a class name, and aliasing a namespace name. Include files will NOT inherit the namespace importing of parent’s rules.

NOTE: $a=’\my\username’; but $a=“\\my\\username”;

PHP and php are reserved for internal namespace use by PHP.

namespace my\name; // define the current namespace

class MyClass {}
function myfunction() {}
const MYCONST = 1;

$a = new MyClass;
$c = new \my\name\MyClass; // fully qualified name

$a = strlen(‘hi’); // fallback to global if strlen is NOT defined in the current namespace

$d = namespace\MYCONST; // namespace keyword => current namespace

$d = __NAMESPACE__ . ‘\MYCONST’;  // must be single quotedecho constant($d);
namespace foo;
use My\Full\Classname as Another;

// use of the leading backslash is NOT required and recommended
use My\Full\NSname;  (not affected by the namespace the code is within i.e. foo)

// importing a global class
use \ArrayObject;

$obj = new namespace\Another; // instantiates object of class foo\Another
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the “use \ArrayObject” we would instantiate an object of class foo\ArrayObject


Assign by Reference

$a =& $b;

$a and $b are completely equal here. $a is not pointing to $b or vice versa. $a and $b are pointing to the same place.

Pass by Reference

function foo(&$var){
foo($a);  // no need & before foo, E_DEPRECIATED/Fatal Error

pass a variable by reference to a function so the function can modify the variable

Return by Reference

class foo {
public $value = 42;
public function &getValue() {
return $this->value;
$obj = new foo;
$myValue = &$obj->getValue(); // $myValue is a reference to
$myValue1 = $obj->getValue();
$obj->value = 2;
echo $myValue;  //2
echo $myValue1;  //42

returning by reference is useful when you want to use a function to find to which variable a reference should be bound, similar to run-time late binding

Userland Rules

Userland refers to applications running in the user space (i.e. codes created/installed by user).

Global Namespace Constructs (once created will have a global namespace):

  • Functions
  • Classes
  • Interfaces
  • Constants (excluding class constants)
  • Variables defined outside classes/functions

Functions use underscores between words, classes use camelCase, interfaces with capitalize CamelCase
Double underscore is reserved for ‘magical’ symbols or methods


The PHP source bundle comes with around 86 extensions (the Core Extensions for arrays, classes, objects, etc.), having an average of about 30 functions each.

Extensions statically compiled into PHP can be initialized using –enable-extname or –with-extname. Others need to be added and configured in php.ini file.

PEAR (PHP Extension and Application Repository) is a repository/library of codes written in php for common functions. It has since evolved into a channel/packaging system which can distribute 3rd party libraries such as PECL.

PECL (PHP Extension Community Library) is written in C which makes use of the PEAR packaging system. PECL makes it easy to create shared PHP extensions. Using the pecl command, do the following:

$ pecl install extname

This will download the source for extname, compile, and install into your extension_dir. may then be loaded via php.ini (add an line)

PHP’s core is made up of two separate pieces. At the lowest levels you find the Zend Engine (ZE). ZE handles parsing a human-readable script into machine-readable tokens, and then executing those tokens within a process space. ZE also handles memory management, variable scope, and dispatching function calls.

The other half of this split personality is the PHP core. PHP handles communication with, and bindings to, the SAPI layer (Server Application Programming Interface, also commonly used to refer to the host environment – Apache, IIS, CLI, CGI, etc). It also provides a unified control layer for safe_mode and open_basedir checks, as well as the streams layer which associates file and network I/O with userspace functions like fopen(), fread(), and fwrite().

When a given SAPI starts up, for example in response to /usr/local/apache/bin/apachectl start, PHP begins by initializing its core subsystems. Towards the end of this startup routine, it loads the code for each extension and calls their Module Initialization routine (MINIT). This gives each extension a chance to initialize internal variables, allocate resources, register resource handlers, and register its functions with ZE, so that if a script calls one of those functions, ZE knows which code to execute.

Once the request is initialized, ZE takes over by translating the PHP script into tokens, and finally to opcodes which it can step through and execute.


The configuration file (php.ini) is read when PHP starts up which is automatically searched for in the same directory of php or server root in the order:

  • SAPI module
  • phprc variable
  • registry keys
  • HKEY_LOCAL_MACHINE\software\php
  • working directory
  • directory (server or php)
  • WIN directory

Since PHP 5.3.0, PHP includes support for .htaccess-style INI files on a per-directory basis by the CGI SAPI (named .user.ini as default, can be renamed using user_ini.filename, reading frequency dictated by user.cache_ttl). For Apache, use .htaccess.

Modes of php directives may belong to one of the following:

PHP_INI_USER Entry can be set in user scripts (like with ini_set()) or in the Windows registry. Since PHP 5.3, entry can be set in .user.ini
PHP_INI_PERDIR Entry can be set in php.ini, .htaccess, httpd.conf or .user.ini (since PHP 5.3)
PHP_INI_SYSTEM Entry can be set in php.ini or httpd.conf
PHP_INI_ALL Entry can be set anywhere

List of php.ini directives

When using PHP as an Apache module, you can also change the configuration settings using directives in Apache configuration files (e.g. httpd.conf) and .htaccess files. You will need “AllowOverride Options” or “AllowOverride All” privileges to do so. An example of such apache configuration:

<IfModule mod_php5.c>
php_value include_path ".:/usr/local/lib/php" [php_value name value]
php_flag engine on [php_flag name on|off]

<IfModule mod_php4.c>
php_admin_value include_path “.:/usr/local/lib/php”
php_admin_flag engine on

register_globals is off by default meaning index.php?get=done can only be accessed by $_GET[‘get’] but not $get
magic_quotes_gpc is off (as deprecated in PHP 5.3.0)
register_long_arrays ($HTTP_*_VARS) is deprecated in PHP 5.3.0 and removed in 5.4.0
variables_order EGPCS tells the server to parse the variables in the order Environment, Get, Post, Cookie and Server (the last one always overwrite for the same name of variables), if not specified, the type of variables will not be parsed at all

Performance – Garbage Collection Mechansim

A) Reduced Memory Usage

Implementing the garbage collection mechanism reduces memory usage by cleaning up circular-referenced variables as soon as the prerequisites are fulfilled. In PHP’s implementation, this happens as soon as the root-buffer is full, or when the function gc_collect_cycles() is called.

With recording of possible roots in PHP 5.3, garbage collection is more efficient in reducing the risk of memory leaks and thus less memory is used. Although the recording of possible roots compared to not recording them at all, like in PHP 5.2, is slower, other changes to the PHP runtime in PHP 5.3 prevented this particular performance loss from even showing.

B) Run-time Delays

Garbage collection hinders performance owning to increased time for the execution of extra processes.


In general the garbage collector in PHP will only cause a slowdown when the cycle collecting algorithm actually runs, whereas in normal (smaller) scripts there should be no performance hit at all.

However, in the cases where the cycle collection mechanism does run for normal scripts, the memory reduction it will provide allows more of those scripts to run concurrently on your server, since not so much memory is used in total.

The benefits are most apparent for longer-running scripts, such as lengthy test suites or daemon scripts.

Opcode Caching

The performance of the PHP script can be improved drastically. The execution process of PHP is done in two steps, i.e., first the PHP code, written in plain-text, is compiled to opcodes and then those opcodes are executed.

When you have one PHP script, as long as it is not modified, the opcodes will always be the same. Hence, in the compilation phase, each time that script is to be executed. It is the waste of CPU-time. To prevent this redundant-compilation, there are various opcode caching mechanisms.

Once the PHP script has been compiled to opcodes, these opcodes are kept into the RAM. These are directly used from memory from the next time the script is executed. This prevents the compilation from being done again and again.

The opcode cache which is used the most is APC – Alternative PHP Cache. Just install APC and code the PHP files as usual, APC will take care of the cache mechanism.



You can read more about my PHP Certification exam journey here.

Support website running for FREE, thanks!

If you find this post helpful and if you are thinking of buying from Amazon, please support the running cost of this website at no extra cost to you by searching and buying through the search box below. Thank you very much for your help!

Edward Chung

Edward Chung aspires to become a full-stack web developer and project manager. In the quest to become a more competent professional, Edward studied for and passed the PMP Certification, ITIL v3 Foundation Certification, PMI-ACP Certification and Zend PHP Certification. Edward shares his certification experience and resources here in the hope of helping others who are pursuing these certification exams to achieve exam success.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

4 Responses

  1. Tester says:

    Guys, be careful, article not checked for errors. For example at part “Return by Reference” there is error on line 9, where is
    $myValue1 = &$obj->getValue();
    should be
    $myValue1 = $obj->getValue();

  2. Shubham Y says:

    Thank You so much chi wing chug for your valuable note’s.
    Please give your email-id or contact me i have several issue regarding this exam.

  3. Amruta Karnik says:

    Thank you very much for sharing the notes! This is very helpful!