PHP cheat sheet

A quick reference for PHP with the most important commands and options. Read it online below, or download the printable PDF.

Download PDF

Hello World

<?php
echo 'Hello, World!';

PHP Tags

Tag Description
<?php Standard opening tag
<?= $foo Short echo tag
<? Short opening tag (discouraged)
?> Standard closing tag

Variables

$greeting = 'Hello, World!';
echo $greeting; // Hello, World!

Constants

const CONSTANT = 'value';
define('RUNTIME_CONSTANT', CONSTANT);

echo CONSTANT; // value
echo RUNTIME_CONSTANT; // value

Strings

$name = 'World';
echo 'Hello, $name!'; // Hello, $name!
echo "Hello, $name!"; // Hello, World!
echo "Hello, {$name}!"; // Hello, World!

echo <<<END
This is a multi-line string
in HEREDOC syntax (with interpolation).
END;

echo <<<'END'
This is a multi-line string
in NOWDOC syntax (without interpolation).
END;

Integers

Notation Description
1234 Decimal (base 10) notation
0123 Octal (base 8) notation
0o123 Octal notation  PHP 8.1
0x0A Hexadecimal (base 16) notation
0b1010 Binary (base 2) notation
10_000 Thousands separator  PHP 7.4

Floating point numbers

Notation Description
1.234 Decimal notation
1.2e3 1200 (scientific notation)
7E-3 0.007 (scientific notation)

Arrays

$array = [1, 2, 3];
$array[] = 4;
$array[4] = 5;

Functions

function foo(int $a, int $b = 5): int
{
    return $a + $b;
}

foo(1, 2); // 3
foo(1); // 6

Named Parameters  PHP 8.0

function foo(string $a = 'Hello', string $b = 'all')
{
    return $a . ' ' . $b;
}

foo(b: 'World!'); // Hello World!

Anonymous Functions (Closures)

$y = 3;
$foo = function(int $x) use ($y): int {
    return $x + $y;
};
$foo(1); // 4

Arrow Functions  PHP 7.4

$foo = fn(int $x): int => $x + $y;

Pipe Operator  PHP 8.5

echo ' Hello World! ' |> 'trim'
    |> strtolower(...); // hello world!

Partial Function Application  PHP 8.6

$isNew = version_compare(?, '8.6', '>=');
array_filter($versions, $isNew);

Generators

function generate(): iterable
{
    yield 1;
    yield 2;
}

foreach (generate() as $value) {
    echo $value;
}

Comments

// This is a one line C++ style comment
# This is a one line shell-style comment
/* This is a
   multi-line comment */

/** @param string[] $bar */
function foo(array $bar): void {}

Atomic / Built-in Types

Type Description
null NULL (no value)
bool Boolean (true or false)
int Integer
float Floating point number
string String
array Array
object  PHP 7.1 Object
resource Reference to an external resource
callable Callback function
void  PHP 7.1 Function does not return a value
never  PHP 8.1 Function never terminates
false  PHP 8.0 false
true  PHP 8.2 true

Composite Types & Type Aliases

Type Description
?string  PHP 7.1 Nullable type: string or null
string|bool  PHP 8.0 Union type: string or bool
Foo&Bar  PHP 8.1 Intersection type: Foo and Bar
(A&B)|null  PHP 8.2 Disjunctive Normal Form (DNF)
iterable  PHP 7.1 array or Traversable
mixed  PHP 8.0 Any type

If/Else

if ($a > $b) {
    echo "a is greater than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is less than b";
}

While

while ($i < 10) {
    echo $i++;
}

Do/While

do {
    echo $i++;
} while ($i < 10);

For

for ($i = 0; $i < 10; $i++) {
    echo $i;
}

Foreach

foreach ($array as $value) {
    echo $value;
}

foreach ($array as $key => $value) {
    echo "$key: $value";
}

Switch

switch ($i) {
    case 0:
    case 1:
        echo "i equals 0 or 1";
        break;
    default:
        echo "i is not equal to 0 or 1";
}

Match  PHP 8.0

$foo = match ($i) {
    0 => "i is 0",
    1, 2 => "i is 1 or 2",
    default => "i is not 0, 1 or 2",
};

Enumerations  PHP 8.1

enum Suit {
    case Hearts;
    case Diamonds;
    case Clubs;
    case Spades;
}

$suit = Suit::Hearts;
$suit->name; // Hearts

Backed Enumerations  PHP 8.1

enum Suit: string {
    case Hearts = '♥';
    case Diamonds = '♦';
    case Clubs = '♣';
    case Spades = '♠';
}

$hearts = Suit::from('♥');
$hearts->value; // '♥'

Language Constructs

Construct Description
echo $string Output one or more strings
print $string Output a string and return 1
unset($var) Destroy the specified variable(s)
isset($var) Determine if a variable is set
empty($var) Determine if a variable is empty
die() Output a message and terminate
exit() Output a message and terminate
include <file> Include and evaluate a file
require <file> Include a file or error on failure
include_once <file> Include and evaluate a file once
require_once <file> Include once or error on failure
clone($obj, $properties) Clone $obj but override some properties  PHP 8.5

Object-Oriented Programming

interface FooInterface
{
    public function baz(): string;
}

class Foo extends Bar implements FooInterface
{
    private string $bar;

    public const string BAZ = 'Hello, ';

    public function __construct(string $bar)
    {
        $this->bar = $bar;
    }

    public function baz(): string
    {
        return self::BAZ . $this->bar;
    }
}

$foo = new Foo("World!");
echo $foo->baz(); // Hello, World!'
echo Foo::BAZ; // Hello, 

Class Keywords

Keyword Description
abstract Cannot be instantiated
final Cannot be extended
extends Extends another class
implements Implements an interface
readonly  PHP 8.2 All properties are read-only

Method keywords

Keyword Description
static Can be called statically, cannot access $this
abstract Must be implemented by subclasses
final Subclasses cannot override

Property Keywords

Keyword Description
static Can be accessed statically
readonly  PHP 8.1 Can only be initialized once
final  PHP 8.4 Subclasses cannot override

Method/Property/Constant Visibility

Keyword Accessible from
public Anywhere
protected The current class and subclasses
private The current class only

Constructor Property Promotion  PHP 8.0

class Foo
{
    public function __construct(private int $a) {}
}

Property Hooks  PHP 8.4

class Foo
{
    public string $name {
        // (string $value) can be omitted
        set (string $value) {
            $this->name = strtolower($value);
        }
        // Short (closure-style) syntax
        get => ucfirst($this->name);
    }
}

Asymmetric Visibility  PHP 8.4

class Foo
{
    public private(set) string $bar = 'baz';
}
$foo = new Foo();
echo $foo->bar; // baz
$foo->bar = 'Foobar'; // Error

Calling Methods/Properties/Constants

Syntax Calls method foo() on:
$foo->foo() The object referenced by $foo
$this->foo() The current object ($this)
Foo::foo() The class Foo
self::foo() The current class
parent::foo() The parent (extended) class
static::foo() The called class
$className::foo() The class stored in $className

Namespacing and Importing

namespace Foo\Bar;

use Foo\Baz as BazAlias;
use Foo\Baz\{Qux, Quux};
use function strlen;
use const PHP_EOL;

Exceptions

try {
    throw new Exception('Something went wrong');
} catch (Exception $e) {
    // Code that runs when an exception is thrown
} finally {
    // Code that will always run
}

Traits

trait FooTrait
{
    public function baz(): string { ... }
}
class Foo
{
    use FooTrait;
}

Attributes  PHP 8.0

#[Attribute(flags: Attribute::TARGET_CLASS)]

Arithmetic Operators

Operator Description
$a + $b Addition
$a - $b Subtraction
$a * $b Multiplication
$a / $b Division
$a % $b Modulo (remainder of $a divided by $b); negative if $a is negative
$a ** $b Exponentiation (raising $a to the power of $b)

Bitwise Operators

Operator Description
& And
| Or (inclusive)
^ Xor (exclusive)
~ Not
<< Shift left
>> Shift right

Comparison Operators

Operator Description
$a == $b $a is equal to $b
$a === $b $a is identical to $b (same type)
$a != $b $a is not equal to $b
$a <> $b $a is not equal to $b
$a !== $b $a is not identical to $b
$a < $b $a is less than $b
$a > $b $a is greater than $b
$a <= $b $a is less than or equal to $b
$a >= $b $a is greater than or equal to $b
$a <=> $b Spaceship: returns -1, 0, or 1 if $a is less than, equal to, or greater than $b

Assignment Operators

Operator Description
$a = $b Assign the value of $b to $a
$a = &$b Assign $b to $a by reference
$a += $b Assign sum of $a and $b to $a
$a -= $b Subtract $b from $a
$a *= $b Assign product of $a and $b to $a
$a /= $b Assign division of $a by $b to $a
$a %= $b Assign $a modulus $b to $a
$a **= $b Assign $a ** $b to $a
$a &= $b Bitwise and and assign
$a |= $b Bitwise or and assign
$a ^= $b Bitwise xor and assign
$a <<= $b Bitwise shift left and assign
$a >>= $b Bitwise shift right and assign

Incrementing/Decrementing Operators

Operator Description
++$a Increments by 1, then returns $a
$a++ Returns $a, then increments by 1
--$a Decrements by 1, then returns $a
$a-- Returns $a, then decrements by 1

Logical Operators

Operator Description
$a and $b $a and $b are true
$a or $b $a and/or $b is true
$a xor $b Either $a or $b is true (not both)
!$a $a is not true
$a && $b $a and $b are true
$a || $b $a and/or $b is true

Note that and, or, and xor have lower precedence than assignment operators, so $a = false or true results in $a = false.

String Operators

Operator Description
$a . $b Concatenate $a and $b
$a .= $b Append $b to $a

Other Operators

Operator Description
$a ? $b : $c Ternary operator: return $b if $a is true, otherwise return $c
$a ?: $b Short ternary: return $a if $a is true, otherwise return $b
$a ?? $b Null coalescing: return $a if $a is not null, otherwise return $b
$a ??= $b  PHP 7.4 Null coalescing assignment: assign $b to $a if $a is null
$a?->b  PHP 8.0 Nullsafe: return $a->b if $a is not null, otherwise return null
@ Suppress errors in the following expression
$a instanceof $b True if $a is an instance of $b
$a |> $callable  PHP 8.5 Apply $callable to $a

Command Line Interface (CLI)

Command Description
php <file> Parse and execute <file>
php -l <file> Syntax check <file>
php -r <code> Run PHP <code> without using script tags
php -a Run an interactive shell
php -S <addr>:<port> Start built-in web server
php -S <addr>:<port> -t <dir> Start built-in web server and specify document root
php -m Show loaded modules
php -i Show configuration information
php -v Show PHP version
php -h Show help

String Functions

Function Description
strlen($string) Return length of $string
str_replace($search, $replace, $subject) Replace $search with $replace in $subject
strstr($haystack, $needle) Return part of $haystack after $needle
substr($string, $start, $length) Return part of $string starting at $start
strtolower($string) Return $string in lowercase
strtoupper($string) Return $string in uppercase
trim($string) Trim whitespace from $string
ltrim($string) Trim whitespace from the left of $string
rtrim($string) Trim whitespace from the right of $string
explode($delimiter, $string) Split $string into an array by $delimiter
implode($glue, $array) Join $array into a string with $glue
str_repeat($string, $multiplier) Repeat $string $multiplier times

Math Functions

Function Description
abs($num) Return absolute value of $num
round($num) Round $num to nearest integer
ceil($num) Round $num up
floor($num) Round $num down
max($a, $b) Return the greater of $a and $b
min($a, $b) Return the lesser of $a and $b
clamp($num, $min, $max)  PHP 8.6 Limit $num to the range $min..$max
pow($a, $b) Return $a to the power of $b
rand($min, $max) Return a random integer between $min and $max
sqrt($num) Return square root of $num

Array Functions

Function Description
count($array) Count elements in $array
sort($array) Sort $array
array_merge($arr1, $arr2) Merge $arr1 and $arr2
array_map($callback, $array) Apply $callback to each element of $array
array_filter($array, $callback) Return elements of $array for which $callback returns true
array_find($array, $callback)  PHP 8.4 Return first element of $array for which $callback returns true
array_find_key($array, $callback)  PHP 8.4 Return key of the first element for which $callback returns true
array_first($array)  PHP 8.5 Return the first element
array_last($array)  PHP 8.5 Return the last element
array_any($array, $callback)  PHP 8.4 true if $callback returns true for any element of $array
array_all($array, $callback)  PHP 8.4 true if $callback returns true for all elements of $array
array_reduce($array, $callback, $initial) Reduce $array to a single value using $callback starting with $initial
array_slice($array, $offset, $length) Return part of $array starting at $offset and continuing for $length elements
array_keys($array) Return keys from $array
array_values($array) Return values from $array
array_combine($keys, $values) Return an array of key/value pairs from $keys and $values
array_reverse($array) Return a reversed copy of $array
array_search($needle, $haystack) Return the key of $needle in $haystack
array_unique($arr) Return unique elements in $arr
array_diff($array1, $array2) Return elements of $array1 not in $array2
array_intersect($array1, $array2) Return elements of $array1 also in $array2

Filesystem Functions

Function Description
file_exists($filename) Return true if $filename exists
is_dir($filename) Return true if $filename is a directory
is_file($filename) Return true if $filename is a regular file
is_readable($filename) Return true if $filename is readable
is_writable($filename) Return true if $filename is writable
mkdir($pathname) Create directory named $pathname
rmdir($dirname) Remove directory named $dirname
unlink($filename) Remove file named $filename
file_get_contents($filename) Return contents of $filename
file_put_contents($filename, $data) Write $data to $filename

php.ini Directives

Directive Description
date.timezone Set default timezone
error_reporting Set error reporting level (e.g. E_ALL, E_ERROR)
display_errors Whether to display errors (e.g. On or Off)
error_log Set error log file (e.g. /var/log/php.log)
xdebug.mode Mode (e.g. debug, develop, profile)
xdebug.discover_client_host Enable Xdebug to discover client host automatically

Enable Xdebug Step Debugging

XDEBUG_MODE=debug XDEBUG_SESSION=1 php <file>

Or for web applications using a browser extension: Firefox Helper Chrome Helper