PHP Cheat Sheet

Hello World

<?php
echo 'Hello, World!';

PHP Tags

TagDescription
<?phpStandard opening tag
<?= $fooShort 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

ExampleValue
2828
10_000 (PHP 7.4)10000
-28-28
01210 (octal)
0x0A10 (hexadecimal)
0b101010 (binary)

Floats

ExampleValue
1.2341.234
-1.2-1.2
1.2e31200 (scientific notation)
7E-30.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, string $b): string
{
return $a . $b;
}
foo(b: 'World!', a: 'Hello, '); // 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)

$y = 3;
$foo = fn(int $x): int => $x + $y;
$foo(1); // 4

Generators

function generate(): interable
{
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 */

/**
* This is a PHPDoc docblock
* @param string[] $bar
* @return void
*/
function foo(array $bar): void
{}

Atomic / Build-in Types

TypeDescription
nullNULL (no value)
boolBoolean (true or false)
intInteger
floatFloating point number
stringString
arrayArray
object (PHP 7.1)Object
resourceReference to an external resource
callableCallback 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

TypeDescription
?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)
interable (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

ConstructDescription
echo $stringOutput one or more strings
print $stringOutput a string and return 1
unset($var)Destroy the specified variable(s)
isset($var)Determine if a variable is set
empty($var)Detemine if a variable is empty
die()Output a message and terminate
exit()Output a message and terminate
include <file>Include and evaluate a file or throw a warning if it fails
require <file>Include and evaluate a file or throw an error if it fails
include_once <file>Include and evaluate a file once only or throw a warning if it fails
require_once <file>Include and evaluate a file once only or throw an error if it fails

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

KeywordDescription
abstractCannot be instantiated
finalCannot be extended
extendsExtends another class
implementsImplements an interface
readonly (PHP 8.2)All properties are read-only

Method keywords

KeywordDescription
staticCan be called statically, cannot access $this
abstractMust be implemented by subclasses
finalSubclasses cannot override

Property Keywords

KeywordDescription
staticCan be accessed statically
readonly (PHP 8.1)Can only be set in the constructor

Method/Property/Constant Visibility

KeywordAccessible from
publicAnywhere
protectedThe current class and subclasses
privateThe current class only

Constructor Property Promotion (8.0)

class Foo
{
public function __construct(private string $bar)
{}
}

Property Hooks (PHP 8.4)

class Foo
{
public string $name {
set (string $value) {
$this->name = strtolower($value);
}
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

SyntaxCalls 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

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)]
class MyClassAttribute
{}

Arithmetic Operators

OperatorDescription
+Addition
Subtraction
*Multiplication
/Division
%Modulus
** Exponentiation

Bitwise Operators

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

Assignment Operators

OperatorDescription
=Assign
+=Add and assign
-=Substract and assign
*=Multiply and assign
/=Divide and assign
%=Modulus and assign
**=Exponent and assign
&=Bitwise and and assign
|=Bitwise or and assign
^=Bitwise xor and assign
<<=Bitwise shift left and assign
>>=Bitwise shift right and assign

Comparison Operators

OperatorDescription
==Equal (values are converted)
===Identical (values and types match)
!=Not equal
<>Not equal
!==Not identical
<Less than
>Greater than
<=Less than or equal to
>=Greater than or equal to
<=>Returns -1, 0, or 1 if the first value is less than, equal to, or greater than the second value

Incrementing/Decrementing Operators

OperatorDescription
++$aIncrements $a by one, then returns $a
$a++Return $a, then increments $a by one
–$aDecrements $a by one,then returns $a
$a–Returns $a, then decrements $a by one

Logical Operators

OperatorDescription
andAnd
orOr
xorExclusive or
!Not
&&And
||Or

String Operators

OperatorDescription
.Concatenate
.=Concatenate and assign

Other Operators

OperatorDescription
$a ? $b : $cTernary operator: return $b if $a is true, otherwise return $c
$a ?: $bShort ternary: return $a if $a is true, otherwise return $b
$a ?? $bNull coalescing: return $a if $a is not null, otherwise return $b
$a ??= $bNull coalescing assignment: assign $b to $a if $a is null
$a?->bNullsafe: return $a->b if $a is not null, otherwise return null
$a = & $bAssign $b by reference to $a
@Suppress errors in the following expression
instanceofReturns true if the left operand is an instance of the right operand

Command Line Interface (CLI)

CommandDescription
php <file>Parse and execute <file>
php -l <file>Syntax check <file>
php -r <code>Run PHP <code> without using script tags
php -aRun 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 -mShow loaded modules
php -iShow configuration information
php -vShow PHP version
php -hShow help

String Functions

FunctionDescription
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)Return $string with whitespace trimmed
ltrim($string)Return $string with left whitespace trimmed
rtrim($string)Return $string with right whitespace trimmed
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

FunctionDescription
abs($num)Return absolute value of $num
round($num)Round $num to the 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
pow($a, $b)Return $a raised to the power of $b
rand($min, $max)Return a random number between $min and $max
sqrt($num)Return square root of $num

Array Functions

FunctionDescription
count($array)Count elements in $array
sort($array)Sort $array
array_merge($array1, $array2)Merge $array1 and $array2
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 of $array for which $callback returns true
array_any($array, $callback) (PHP 8.4)Return true if $callback return true for any element of $array
array_all($array, $callback) (PHP 8.4)Return true if $callback return 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 an array of keys from $array
array_values($array)Return an array of 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($array)Return a copy of $array with duplicate values removed
array_diff($array1, $array2)Return elements of $array1 not in $array2
array_intersect($array1, $array2)Return elements of $array1 also in $array2

Filesystem Functions

FunctionDescription
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

DirectiveDescription
date.timezoneSet default timezone
error_reportingSet error reporting leve (e.g. E_ALL, E_ERROR)
display_errorsWhether to display errors (e.g. On or Off)
error_logSet error log file (e.g. /var/log/php.log)
xdebug.modeMode (e.g. debug, develop, profile)
xdebug.discover_client_hostEnable 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.

Data from: https://nth-root.nl/en/cheat-sheets (thank you).