Cheatsheets / PHP

PHP Cheatsheet

Complete PHP reference. Hit Ctrl+P to print.

Variables & Types

$name = valueVariable assignment — $ prefix required
$x = 42Integer
$x = 3.14Float
$x = "hello"String (double quotes allow interpolation)
$x = 'hello'String (single quotes — literal, no interpolation)
$x = true / falseBoolean
$x = nullNull — absence of a value
$x = [1, 2, 3]Array literal
gettype($x)Returns type as string: "integer", "double", "string", "boolean", "array", "NULL"
is_int($x) / is_float($x) / is_string($x)Type-check functions
is_null($x) / is_array($x) / is_bool($x)More type-check functions
isset($x)True if variable exists and is not null
empty($x)True if falsy: 0, "", "0", [], null, false
(int) $x / (string) $x / (float) $xCast to type
intval($x) / strval($x) / floatval($x)Convert to type via function
const MAX = 100Global constant (no $ prefix)
define("MAX", 100)Runtime constant definition

Strings

"Hello, $name!"Variable interpolation in double-quoted strings
"Hello, {$obj->name}!"Expression interpolation with curly braces
$a . $bString concatenation with dot operator
strlen($s)Number of bytes (use mb_strlen() for multibyte)
strtolower($s) / strtoupper($s)Change case
ucfirst($s) / ucwords($s)Capitalise first letter / each word
trim($s) / ltrim($s) / rtrim($s)Strip whitespace from both / left / right
str_contains($s, "sub")True if substring found (PHP 8+)
str_starts_with($s, "pre") / str_ends_with($s, "suf")Check prefix/suffix (PHP 8+)
strpos($s, "sub")First position of substring (false if not found)
substr($s, 2, 5)Extract substring: start offset, length
str_replace("a", "b", $s)Replace all occurrences
str_ireplace("a", "b", $s)Case-insensitive replace
explode(",", $s)Split string into array on delimiter
implode(", ", $arr)Join array into string with glue
sprintf("Hello %s, you are %d", $name, $age)Format string
number_format(1234567.891, 2)Format number: "1,234,567.89"
htmlspecialchars($s)Escape HTML entities — use before outputting user input
nl2br($s)Insert
before newlines
str_pad($s, 10, "0", STR_PAD_LEFT)Pad string to length
str_repeat("ab", 3)Repeat string N times: "ababab"
preg_match("/pattern/", $s)Test regex match — returns 1 or 0
preg_replace("/pattern/", "replace", $s)Regex replace
preg_split("/[\s,]+/", $s)Split by regex

Arrays

$arr = [1, 2, 3]Indexed array
$map = ["key" => "val"]Associative array (key => value)
$arr[] = 4Append to array
count($arr)Number of elements
array_push($arr, 4, 5)Push one or more values onto end
array_pop($arr)Remove and return last element
array_shift($arr)Remove and return first element
array_unshift($arr, 0)Prepend element(s) to start
in_array("val", $arr)True if value exists in array
array_key_exists("key", $map)True if key exists
array_keys($map)Array of all keys
array_values($arr)Re-indexed array of all values
array_merge($a, $b)Merge arrays (numeric keys re-indexed)
array_slice($arr, 1, 3)Extract portion: start offset, length
array_splice($arr, 1, 2, ["x"])Remove and/or insert elements (mutates)
array_map(fn($x) => $x * 2, $arr)Transform each element
array_filter($arr, fn($x) => $x > 2)Filter elements by callback
array_reduce($arr, fn($carry, $x) => $carry + $x, 0)Reduce to single value
sort($arr) / rsort($arr)Sort ascending / descending (mutates, re-indexes)
asort($arr) / arsort($arr)Sort preserving keys
ksort($map) / krsort($map)Sort by key
usort($arr, fn($a, $b) => $a - $b)Sort with custom comparator
array_unique($arr)Remove duplicate values
array_flip($arr)Swap keys and values
array_reverse($arr)Reverse order
array_chunk($arr, 3)Split into chunks of size N
array_combine($keys, $vals)Create associative array from two arrays
array_search("val", $arr)Key of first matching value (false if not found)
compact("name", "age")Create array from variable names
extract($map)Import array keys as variables into scope

Control Flow

if ($x > 0) { } elseif ($x < 0) { } else { }Conditional branches
$x > 0 ? "pos" : "neg"Ternary operator
$x ?: "default"Elvis operator — returns $x if truthy, else "default"
$x ?? "default"Null coalescing — returns $x if set and not null
$x ??= "default"Null coalescing assignment
match ($x) { 1 => "one", 2 => "two", default => "other" }match expression — strict comparison, no fallthrough
switch ($x) { case 1: break; default: }switch — loose comparison, falls through without break
for ($i = 0; $i < 10; $i++) { }C-style for loop
foreach ($arr as $val) { }Iterate array values
foreach ($map as $key => $val) { }Iterate key => value pairs
while ($x > 0) { }Loop while condition is true
do { } while ($x > 0)Execute at least once, then check condition
break / break 2Exit loop (break 2 exits two levels)
continue / continue 2Skip to next iteration
return $valueReturn value from function

Functions

function add(int $a, int $b): int { return $a + $b; }Named function with type hints
function greet(string $name = "World"): string { }Default parameter value
function sum(int ...$nums): int { return array_sum($nums); }Variadic — collects extra args as array
function log(string $msg, bool $verbose = false): void { }void return type
fn($x) => $x * 2Arrow function (short closure, captures outer scope by value)
function($x) use ($multiplier) { return $x * $multiplier; }Anonymous function capturing outer variable
add(b: 2, a: 1)Named arguments (PHP 8+) — order independent
function foo(?string $s): ?int { }Nullable type — allows null in addition to declared type
function foo(int|string $x): void { }Union types (PHP 8+)
function foo(mixed $x): never { }mixed accepts any type; never means function always throws/exits
function &getRef(): string { return $this->name; }Return by reference
function foo(array &$arr): void { }Parameter passed by reference

Classes & OOP

class Dog extends Animal implements Runnable { }Class declaration with inheritance and interface
public function __construct(private string $name) { }Constructor property promotion (PHP 8+)
$dog = new Dog("Rex")Instantiate object
$dog->name / $dog->bark()Access property / call method
Dog::MAX_AGE / Dog::create()Access static property / static method
$this->nameCurrent instance property
parent::__construct($args)Call parent constructor
self::$count / static::$countself:: resolves at definition time; static:: resolves at runtime (late static binding)
public / protected / privateVisibility: public=anywhere, protected=class+subclasses, private=class only
readonly string $nameProperty can only be written once in constructor
abstract class Shape { abstract public function area(): float; }Abstract class — cannot be instantiated
interface Drawable { public function draw(): void; }Interface — defines contract, no implementation
trait Loggable { public function log(): void { } }Trait — reusable method bundle
use Loggable;Include trait in a class
enum Status { case Active; case Inactive; }Backed enum (PHP 8.1+)
enum Color: string { case Red = "red"; case Blue = "blue"; }String-backed enum
Status::Active / Color::Red->valueAccess enum case / backed value
$obj instanceof ClassNameCheck if object is instance of class
clone $objShallow copy of object
public function __toString(): string { }Magic method — called when object cast to string
public function __get($name) / __set($name, $val)Magic property access

Error Handling

try { } catch (Exception $e) { } finally { }Try/catch/finally — finally always runs
catch (TypeError | ValueError $e) { }Catch multiple exception types (PHP 8+)
throw new Exception("message")Throw an exception
throw new InvalidArgumentException("bad arg")Specific exception types
$e->getMessage() / $e->getCode() / $e->getTrace()Exception methods
class AppException extends RuntimeException { }Custom exception class
set_exception_handler(fn($e) => logger($e->getMessage()))Global uncaught exception handler
error_reporting(E_ALL)Set which errors are reported
trigger_error("msg", E_USER_WARNING)Trigger a user-level error

Common Built-ins

date("Y-m-d H:i:s")Current date/time formatted
time()Current Unix timestamp
strtotime("next Monday")Parse date string to timestamp
json_encode($data)Encode to JSON string
json_decode($json, true)Decode JSON — true returns associative array
var_dump($x)Print type and value — for debugging
print_r($arr)Human-readable array/object print
var_export($x, true)Return parseable PHP representation
rand(1, 100)Random integer between min and max
array_rand($arr)Random key from array
shuffle($arr)Shuffle array in place
round($x, 2) / ceil($x) / floor($x)Round / round up / round down
abs($x) / max($a, $b) / min($a, $b)Absolute value / max / min
file_get_contents($path)Read file into string
file_put_contents($path, $data)Write string to file
file_exists($path)Check if file or directory exists
is_file($path) / is_dir($path)Check if path is a file / directory
unlink($path)Delete a file
glob("*.php")Find files matching pattern
header("Location: /url")Send HTTP header (must be before output)
http_response_code(404)Set HTTP response status code
ob_start() / ob_get_clean()Output buffering — capture output as string
class_exists("ClassName")Check if class is defined
method_exists($obj, "name")Check if method exists on object
function_exists("name")Check if function is defined
call_user_func($callable, ...$args)Call callable dynamically