PHP Cheat Sheet


PHP is a dynamic language, running with PHP processor (interpretor). Similar to ASP, PHP uses pseudo tag <?php / ?> to signify PHP code in the middle of HTML content. This once was a famous style in ASP but it failed eventually when dealing with large scale project since it can hardly be designed in modules.

According to PHP document, close tag ?> can be omitted so guarantee no extra blank on the end of document.


  • - get help of any PHP functions and language spec.


Import other PHP code

include "otherfile.php";
include_once "otherfile.php";

require "otherfile.php";
require_once "otherfile.php";

require throws an exception if file is not found while include just warns with a message.

Module in PHP can *return value*. One can retrieve return value from module by assigning it to a variable.

$value = require_once "somefile.php";

Assuming that somefile.php has return command at its global scope.

More detail, see PHP include document.

Language Spec


  • // C style line comment
  • /* block style */
  • # shell style line comment

Data Types

  • boolean - e.g. False, True. Boolean literal is case-insensitive.
    • Equality: $a == $b
    • Inequality: $a !== $b
    • Implicit coercion: 0, "0", "", NULL, array(), NaN are treated as False
  • integer - e.g. 123, 0123 (octal), 0x123 (hex-decimal), 0b1101 (binary), (int) 1.23 (type cast), intval(1.23) (conversion function).
    • Integer size is platform dependent!!
  • float - e.g. 1.23, 1.2e3, NaN.
    • float size is platform dependent. Though, double-size floating point is usually used.
  • string - also representing array of bytes!! e.g. "Hello", 'hello', "Hello $name, $greeter->greet!" (string interpolation)
    • single-quote string does not expand escape sequence (e.g. \n) and not interpolate string.
    • PHP string is mutable. $name[0] = 32 is valid. {} can be used instead of []. e.g. $name{0} = 32
    • Since representation of string is not clear, there are a lot of string-related functions that assume string in different forms. Some functions work only single-bye array. Some works with unicode. Some works with locale setting. Better check function document before using them. :(
    • support "heredoc/nowdoc" string. The token used after <<< must be valid PHP identifier (i.e. alphabetics or underscore).
$show_var = 'name';
$name = 'RZ';

$heredoc = <<<TOKEN
 multi-line texts.
 Support string interpolation with variable: ($name), ${name}, or {${$show_var}}.

$nowdoc = <<<'TOKEN'
  This is like single-quote string. No $name expansion.
  • Associative array - e.g. array(1,2,3,4,5), array("aa" => 1000, "bb" => 2000) (as Hash!!)
    • PHP >= 5.4, square bracket form can be used: e.g. [1,2,3], ["aa" => 1000, "bb" => 2000].
    • index [] has its own meaning. e.g. $a[] = 123; is to append 123 into the array.
    • String index if containing only digits will be converted to number! So $a['5'] is the same as $a[5].
    • As being associative, index can be changed by explicit a key.
$a = [1,2,3, 10 => 4, 5, 6];
echo $a[10];  // got 4
echo $a[11];  // got 5
  • Object - see Class section below.
    • PHP Object is like Javascript Object where it is opened for modification (and headache).
  • Resource - This is likely a system handle used in interop (e.g. C/C++ library).
  • null - NULL is case-insensitive keyword.

Type casting

According to Type Juggling document, following casts are possible:

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL (PHP 5)

Common Operators

  • var_dump($a) dumping value of a variable.
  • print_r($a) print "human-readable" of a var.


  • . (concatenate) e.g. "Hello" . " " . "World"


  • array_diff($a,$b) - return all members in $a which is not in $b.
  • range(1,5) - is equivalent to writing [1,2,3,4,5]. First parameter is begin number. The last parameter is end number.
  • unset unset array index or remove array entirely. e.g. unset($a[6]), unset($a).


  • $a instanceof ClassA - instanceof checks whether an instance $a can be up-casted to type ClassA. Note that instanceof can also be used with interface.


All variables in PHP is prefixed with $, e.g. $x.

Reference variable

A variable can become a reference variable by referring to other variable with & (ampersand).

$a = 123;
$b = &$a;  // $b is now a reference variable
$b = 456;  // $a now contains 456

Predefined variables

Check out PHP: Predefined Variables document for more detail.

echo $_SERVER['REQUEST_TIME'];  // print server's request time.

Global reference in function

global (case-insensitive) is a keyword to refer outer variable inside a function. $GLOBALS array can also be used!

$x = 1;
function changex() {
  global $x;
  $x += 1;
  // or
  $GLOBALS['x'] += 1;

Static variable in function

static (case-insentive) is a keyword to make a local storage inside a function. Static initializer must always be a constant value.

function counter() {
  static $count = 0;
  static $invalid = 1 + 1;  // error, assignment with an expression.
  return ($count += 1);

Dynamic variable reference (aka Variable Variables)

Variable variables is a way to indirectly refer to a variable.

$a = 123;
$name = 'a';

var_dump($$name);  // show content of $a

$$name = 456;   // now $a is 456.

Class property can also be referenced similarly.

class C {
  var $a = 123;
$c = new C;
$name = 'a';

$c->$name = 555;
$c->{'name'} = 555;  // using expression
echo $c->a;   // show 555

Array unpack (PHP 5.5)

$a = [1,2,3];
list($x,$y,$z) = $a;  // $x = 1, $y = 2, $z = 3

list is a helper keyword to indicate array unpack operation. This feature can also be used in foreach.


define("PI", 3.141);
// or
const PI1 = 3.141;  // PHP >= 5.3
echo PI;  // note that no $ needed.
echo constant("PI");  // same as using PI directly.

Note, PHP < 5.6 only boolean, integer, float, and string can be declared as constant.

To check whether a constant has been defined, use defined().

defined('PI') || define('PI', 3.141);  // defined PI if it has not been defined.

Predefined Constants

See also:

  • __LINE__ - The current line number of the file.
  • __FILE__ - The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
  • __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.
  • __FUNCTION__ - The function name.
  • __CLASS__ - The class name. 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. The trait name includes the namespace it was declared in (e.g. Foo\Bar).
  • __METHOD__ - The class method name.
  • __NAMESPACE__ - The name of the current namespace.


  • Ternary operator: $a? $b : $c.

Namespace (PHP 5.3)

... see


Anonymous function

$f = function($x) { echo "Hello $x\n"; };

To refer variable outside its function scope, declare with use:

$bad_global = 'Hello';

$f = function() use ($bad_global) { echo $bad_global; };

Named function

All PHP functions are global.

function my_func($param1, $param2, $option = true) {
  return $param1 + $param2;

Just like Javascript, a function exists to be called only if its declaration gets executed!

if (false) {
  function mystery() {
    echo 'I cannot be called!';

Variable-length argument list

(PHP 5.6)

function print_to(&$buffer, ...$options) {
  foreach($options as $opt)
    $buffer += $opt;
$b = "";
print_to($b, 1,2,3);

function sum($x, $y){
  return $x + $y;
$p = [123, 456];
echo sum(...$p);   // unpack function arguments

(PHP < 5.6)

function print_to(&$buffer) {
  if (func_num_args() > 1) {
    foreach(func_get_args() as $opt)
      $buffer += $opt;

Type Declaration/Annotation (PHP 5.0)

More info see Function Arguments.

function add(int $x, int $y): int {
  return $x + $y;

Callback / Variable function

Functions can be indirectly called with a string variable:

function myprint(){
  echo "hello";
$any_code = 'myprint';
$any_code();  // Variable function

Object method can be indirectly called with an array:

class A {
  static function static_say() {
    echo 'hello from static';
  function say() {
    echo 'hello from instance';

$x = new A;
$instance = [$x, 'say'];
$static_x = ['A', 'static_say'];
$instance();  // PHP 7(?)
$static_x();  // PHP 7(?)

call_user_func('A::static_say');  // PHP >= 5.2.3

class B extends A {}

call_user_func('B', 'parent::static_say');  // PHP >= 5.3

See also: Variable Function.

Code Control


if ($x > 0) {
  echo "greater than 0"
elseif ($x == 0) {
  echo "equal 0"
else {
  echo "less than 0"

// or...
if ($x > 0):
  echo "greater than 0"
elseif ($x == 0):
  echo "equal 0"
  echo "less than 0"


switch($x) {
case 1: echo '1'; break;
default: echo 'not 1'; break;

C-style for loop

for($var = 1; $var < 10; ++$var) {
  echo "$var\n";


To iterate values in an array:

$a = [1,2,3];
foreach($a as $value) {
  echo "$value\n";

To iterate key/value pairs:

$a = [1 => 'Hello', 2 => 'World'];
foreach($a as $key => $value) {
  echo "$key => $value\n";

C-style while loop

while(True) {
  echo "Infinite.\n";

do {
  echo 'Infinite\n';
} while(True);

Goto (PHP 5.3)

function goto_demo(){
  goto just_wanna_jump;
  echo "Do NOT use GOTO!!!";
  echo 'OK';

Execution Directive



try {
} catch(Exception $ex) {

throw new Exception("Just like C#/Java");


Class property can be declared with public, private, or protected. Before PHP 5, class property is declared with var, which is still compatible.

class A {
  public $x;
  private $y;
  const zzzz = 111;
  static $z = 123;

  function __construct() {
    $this->x = 1;
    $this->y = 123;
  function __destruct() {
    $this->x = 0;

  function show() {
    echo $this->x;
  final function cannot_overriden() {}

  private function myprivate() {}
  protected function myprotected() {}

class B extends A {
  function show() {
    echo 'Show is overriden.';

$a = new A;
echo $a->x;

Property/Method Overloading (PHP 7)

This feature is best to implement proxy object. Not for common usage.


class WeirdPerson {
  private $nick;
  function __get($name) {
    if ($name == 'name') return 'anonymous';
    if ($name == 'nick') return $this->nick;
    return null;
  function __set($name, $value) {
    if ($name == 'nick') $this->nick = $value;
  function __isset($name) {
    return $name == 'name' || ($this->nick && $name == 'nick');
  function __unset($name) {
    if ($name == 'nick') unset($this->nick);
$p = new WeirdPerson;
echo $p->$name;  // anonymous


class Person extends WeirdPerson {
  function __call($name, $args) {
    if ($name == 'greet') 
      echo "$this->name: Hello $args[0]";
  static function __callStatic($name, $args) {
    if ($name == 'greet')
      echo "Hi $args[0]";
$p = new Person;

Abstract class

Like C#, abstract keyword is used to indicate abstract class. If a class contains an abstract method, it must also be an abstract class.

class abstract A {
  abstract public function say_anything();

Final class / method

Keyword final can mark either method or class to disallow extension. If it's used on a class, that class cannot be inherited. If it's used on a method, the method cannot be overridden in derived classes.

Anonymous Class (PHP 7)

$silly = new class {
  function greet() { echo "Hello\n"; }

class A {}
$with_construction = new class('RZ') extends A {
  public $name;
  function __construct($name) {
    $this->name = $name;

Get Class Name

class A {}

$name = A::class;   // string "A"

String representation

Class can implement __toString() to allow conversion of a class to a string.

class A {
  function __toString() {
    return "My name is " . A::class;

Debug Info

Define __debugInfo to specify the properties that should be shown with var_dump().

class A {
  private $a, $b;
  function __debugInfo() {
    // only "a" should be shown.
    // custom debug content for "b"
    return ['a', 'b' => '(hidden)'];

Object as function (PHP 5.3)

__invoke method can be defined so an object can be "callable".

class A {
  function __invoke($x) {
    echo "Hi $x\n";
$a = new A;

Variable Class

class A {}

$class_name = 'A';
$a = new $class_name();


Keyword self and parent can be used in Class context to help with cloning.

class A {
  function clone_me() {
    $new_me = new self;  // new A
    return $new_me;

There is clone keyword which can clone any object.

class Person {
  public $name;
  function __construct($name) { $this->name = $name; }
$p = new Person('RZ');
$q = clone $p;
echo $q->name; // RZ

A class can implement __clone() that is activated after a cloned object is created.

class TalkativePerson extends Person {
  function __clone() {
    echo "I'm a clone of $this->name";


Autoload is a way to resolve unknown class name. Before PHP 5.3, function __autoload() is used to handle this. The newer recommended method is to use spl_autoload_register() instead.

Function that is registered with spl_autoload_register will be called before the resolution fails.

spl_autoload_register(function($classname) {
  include $classname . 'php';  // dynamic load PHP file.

$a = new AClass;   // this trigs the autoload function.

class A extends SomeClass {}  // SomeClass will also trig the autoload.

Late Binding



PHP has similar interface features like Java/C#, but it can also define some constant in interface.

interface iDoable {
  function do_something();

interface iDoMore extends iDoable {
  const NormalTimes = 3;
  function do_more($times = NormalTimes);

Iteration (PHP 5)

All objects in PHP are iterable by default. It uses public properties in iteration (e.g. foreach). By implementing Iterator, a class can custom its iteration behaviors.

class Infinity implements Iterator {
  private $n = 1;
  function current() { return $this->n; }
  function key() { return $this->n; }
  function rewind() { $this->n = 1; }
  function next() { return ++$this->n; }
  function valid() { return true; }
$inf = new Infinity;
foreach($inf as $i)
  echo 'Infinity $i!';

There is also IteratorAggregate which can also be used for iteration.

class ContentBox implements IteratorAggregate {
  private $data = [1,2,3,4,5];
  function getIterator() { return new ArrayIterator($this->data); }


Trait is a group of functions that can be integrated (reuse) in any class.

traits Eatable {
  function eat() {
    echo "Eating $this->favorite";

class Me {
  public $favorite = 'Crabs';

  use Eatable;

More about traits and name resolution see Traits.

Object Serialization

serialize() converts any PHP data into a string representation. unserialize() converts the string back to PHP data.

A class can control serialization by implementing __sleep() and __wakeup() methods. __sleep is called before serialization start and __wakeup is called after object deserialization is done and the new object is ready to go.

function get_new_id(): int { ... }
class A {
  public $name;
  public $id;
  private $secret;
  function __construct() {
  function __sleep() {
    // only $name and $secret should be serialized.
    return ['name', 'secret'];
  function __wakeup() {
    $this->id = get_new_id();

Web interface

Form data from POST/GET is stored in $_REQUEST array and also in $_POST or $_GET respectively. (See Predefined Variables)


HTTP Cookies can be accessed from $_COOKIE and can be set by setcookie() function.

Package Manager

Use composer ...