All cheatsheets

Cheatsheets

PHP

Modern PHP 8: types, arrays, classes & traits, enums, the match expression, Composer, and PDO.

Test yourself

73 entries

Variables, types & strings10

$name = 'Ada'; $ok = true;

Variables start with $; no declaration keyword, dynamically typed.

int float string bool array null object

The scalar & compound types a value can carry.

gettype($x); is_int($x); is_string($x);

Inspect a value's type at runtime — PHP is loosely typed.

declare(strict_types=1);

Opt into strict type checking for scalar type declarations (top of file).

const PI = 3.14; '\'literal $x\''

const = compile-time constant; single quotes do NOT interpolate.

"Hello $name, {$user->name}"

Double quotes interpolate variables; {} braces disambiguate complex expressions.

<<<EOT ... EOT; <<<'EOT' ... EOT;

Heredoc (interpolates) and Nowdoc (literal) for multi-line strings.

$a . $b $s .= $x

Concatenate with the dot; .= appends. trim()/strtolower()/explode() are common helpers.

str_contains($h, $n) str_starts_with() str_ends_with()

PHP 8.0 substring helpers — no more strpos() !== false.

sprintf('%s is %d', $name, $age)

Format strings with type placeholders; printf() echoes directly.

Arrays & array functions8

$nums = [1, 2, 3];

Indexed array (0-based). Short [] syntax preferred over array().

$user = ['name' => 'Ada', 'age' => 36];

Associative array — the workhorse map/dict. Ordered by insertion.

$nums[] = 4; array_push($nums, 5);

Append to an indexed array.

array_map / array_filter / array_reduce

Functional iteration without manual loops.

in_array($v, $arr, true) array_keys() array_values()

Membership & key/value extraction (pass true for strict ===).

count($arr) array_merge($a, $b) array_unique()

Size, merge, dedupe.

[$a, $b] = [1, 2]; ['name' => $n] = $user;

Array/list destructuring, including by key.

$merged = [...$a, ...$b];

Spread operator merges arrays (string keys supported since 8.1).

Functions, arrow fns & null safety10

function greet(string $n): string { return "Hi $n"; }

Typed parameters and return type.

function f(int $a, int $b = 0): int

Default parameter values (must follow required params).

fn($x) => $x * 2

Arrow function (PHP 7.4) — auto-captures outer scope by value.

function sum(int ...$nums): int

Variadic — collect remaining args into an array (splat).

function &ref(array &$a)

Pass/return by reference with & (use sparingly).

function f(): void function f(): never

void = no return; never (8.1) = always throws/exits.

$x = $a ?? 'default';

Null coalescing — value of $a unless it is null OR undefined.

$cache['k'] ??= compute();

Null coalescing assignment — assign only if currently null/unset.

$country = $user?->address?->country;

Null-safe operator (PHP 8.0) — short-circuit the whole chain if any link is null.

isset($a) empty($a)

isset = set & not null; empty = unset OR falsy (0, '', [], '0').

OOP: classes, traits, enums & promotion10

class User { public string $name; public function __construct(string $n) {...} }

Class with typed properties, visibility, and a constructor.

interface Repository { public function find(int $id): ?User; }

Interface — a contract of public method signatures (no bodies).

trait Timestamps { public function touch(): void {...} }

Trait — reusable methods/properties mixed into many classes (horizontal reuse).

abstract class Shape { abstract public function area(): float; }

Abstract class — partial implementation; cannot be instantiated.

class Admin extends User {} parent::m() final class X

Single inheritance via extends; call up with parent::; final blocks subclassing/overriding.

public static function make(): static self:: vs static::

Static members; static:: is late static binding (resolves to called class).

readonly public int $id;

readonly property (8.1) — write once in constructor, then immutable.

public function __construct(private string $name) {}

Constructor property promotion (8.0) — declare + assign properties in the signature.

enum Suit: string { case Hearts = 'H'; case Spades = 'S'; }

Backed enum (8.1) — a fixed set of named, typed constants with methods.

enum Direction { case North; case South; }

Pure (unbacked) enum — cases without scalar values.

Match, named args & type declarations9

setupServer(port: 8080, debug: true);

Named arguments (8.0) — pass by parameter name, skip optional ones, any order.

$type = match($code) { 200, 201 => 'ok', 404 => 'missing', default => '?' };

match (8.0) — expression that returns a value; strict === comparison.

switch ($x) { case 1: ...; break; default: ... }

Classic switch — loose ==, needs break, falls through. Prefer match for new code.

function f(?int $x): ?string

Nullable type with ? — accepts int|null / returns string|null.

function area(int|float $n): int|float

Union types (8.0) — a value may be one of several listed types.

function f(): self / static / parent

Return the class itself; static = late static binding (subclass-aware).

function f(mixed $x): void

mixed (8.0) — any type (explicit 'I accept anything'), better than no hint.

function pipe(callable $fn) function each(iterable $it)

callable accepts functions/closures; iterable = array | Traversable.

true / false / null as standalone types (8.2)

Literal types: function f(): true {} narrows the return.

Namespaces, Composer & exceptions9

namespace App\Service; use App\Model\User;

Namespaces group classes; `use` imports a fully-qualified name into scope.

composer require monolog/monolog

Install a package and add it to composer.json + autoloader.

require_once __DIR__ . '/vendor/autoload.php';

Bootstrap Composer's PSR-4 autoloader — then never write require for classes again.

use Vendor\Pkg\{Foo, Bar};

Group-use imports several symbols from one namespace.

try { ... } catch (Throwable $e) { ... } finally { ... }

Structured error handling; finally always runs.

throw new InvalidArgumentException('bad id');

Throw built-in or custom exceptions; throw is an expression (8.0).

catch (TypeError | ValueError $e)

Multi-catch — handle several exception types in one block (7.1+).

$e->getMessage() $e->getCode() $e->getPrevious()

Inspect the thrown exception; getPrevious() walks the chain.

catch (\Throwable)

Non-capturing catch (8.0) — omit the $var when you don't need it.

PDO database access5

$pdo = new PDO($dsn, $user, $pass, $opts);

Connect with PDO — the portable, driver-agnostic DB layer.

$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?'); $stmt->execute([$id]);

Prepared statements — the ONLY safe way to pass user input to SQL.

$stmt->fetch() $stmt->fetchAll() $stmt->fetchColumn()

Read one row / all rows / a single scalar.

$pdo->beginTransaction(); ... $pdo->commit();

Wrap multiple writes in a transaction — all-or-nothing.

$pdo->lastInsertId() $stmt->rowCount()

Last auto-increment id / rows affected by the last statement.

Superglobals & web6

$_GET['q'] $_POST['name']

Query-string and form-body params — always strings, always untrusted.

$_SERVER['REQUEST_METHOD'] $_SERVER['HTTP_HOST']

Request metadata: method, host, headers (HTTP_*), path.

$_REQUEST $_COOKIE $_SESSION $_FILES $_ENV

Merged GET+POST+COOKIE / cookies / session / uploads / env vars.

session_start(); $_SESSION['user_id'] = 42;

Start/resume a session; $_SESSION persists per-user server-side state.

header('Location: /home'); http_response_code(404);

Send raw headers / set status code (before any output).

json_encode($data) json_decode($json, true)

Serialize to/from JSON; pass true to decode objects as assoc arrays.

Gotchas: loose typing6

== vs ===

== compares values WITH type juggling; === compares value AND type. Prefer ===.

Truthiness: 0, 0.0, '', '0', [], null, false are falsy

Falsy values — note '0' (string zero) and empty array are falsy, but '0.0' and 'false' are truthy.

'10 apples' + 5 // 15 + a warning (8.0)

Leading-numeric strings parse in math; non-numeric throws TypeError (8.0+).

Float precision: 0.1 + 0.2 !== 0.3

Never === floats. Use abs($a-$b) < PHP_FLOAT_EPSILON or bcmath for money.

Arrays are copied by value, objects by handle

Assigning an array copies it; assigning an object copies the reference, not the object.

$a = $b ? : $c // ?: returns $b if truthy

Elvis operator returns the left side when truthy — not the same as ?? (null-only).