PHP Cheatsheet

Control and Functions

Use this PHP reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Conditionals

if ($score >= 90) {
    $grade = 'A';
} elseif ($score >= 80) {
    $grade = 'B';
} else {
    $grade = 'C';
}

$status = $active ? 'on' : 'off';

Match

$label = match ($status) {
    200, 201, 204 => 'success',
    301, 302     => 'redirect',
    404          => 'not found',
    default      => 'error',
};

$grade = match (true) {
    $score >= 90 => 'A',
    $score >= 80 => 'B',
    default      => 'C',
};

match is an expression: it returns a value, compares with strict ===, needs no break, and throws UnhandledMatchError when no arm matches and there is no default. Prefer it over switch in modern code.

Null Handling

$value = $input ?? 'default';        // null coalescing
$config['retries'] ??= 3;            // assign only if null/unset
$city = $user?->address?->city;      // nullsafe: null if any link is null
$len = strlen($name ?? '');

?-> (nullsafe operator) short-circuits the whole chain to null instead of throwing when the left side is null. It works for method calls and property reads, not writes.

Loops

for ($i = 0; $i < 3; $i++) {}
while ($row = fgets(STDIN)) {}
foreach ($items as $item) {}
foreach ($map as $key => $value) {}
foreach ($rows as $row) {
    if ($row === '') continue;   // skip to next iteration
    if ($row === 'END') break;   // exit the loop (break 2 exits two levels)
}

Use foreach for arrays unless you truly need an index.

Functions

function add(int $a, int $b): int {
    return $a + $b;
}

function greet(string $name = 'friend'): string {
    return 'Hello ' . $name;
}

Named Arguments and Variadics

function paginate(array $rows, int $page = 1, int $perPage = 20): array { return []; }

paginate($rows, perPage: 50);        // skip $page, name the rest

function sum(int ...$nums): int {    // variadic: $nums is an array
    return array_sum($nums);
}

sum(1, 2, 3);
sum(...[1, 2, 3]);                   // spread an array into arguments

Default vs Nullable Parameters

function connect(int $timeout = 5): void {}       // optional with fallback
function tag(?string $label): string {            // nullable but required
    return $label ?? 'untitled';
}
function search(string $q, ?int $limit = null): array { return []; }

?int means the value may be null but the caller must still pass something unless a default exists. An explicit = null default makes it optional and nullable.

Anonymous Functions, Arrows, First-Class Callables

$double = function (int $n): int { return $n * 2; };
$plus = function (int $n) use ($base): int { return $n + $base; };
$triple = fn(int $n): int => $n * 3;

$lengths = array_map(strlen(...), $words);   // first-class callable syntax
$fetch = $repo->findById(...);               // method as a closure

Arrow functions capture parent-scope variables by value automatically. name(...) creates a Closure from any function or method and replaces the old 'strlen' / [$obj, 'method'] string callables.

Generators

function lines(string $path): Generator {
    $h = fopen($path, 'r');
    while (($line = fgets($h)) !== false) {
        yield rtrim($line, "\n");
    }
    fclose($h);
}

foreach (lines('big.log') as $line) {}

function counter(): Generator {
    yield 1;
    yield 2;
    yield from [3, 4];   // delegate to another iterable
}

Generators produce values lazily, one at a time, so they iterate huge datasets in constant memory. Any function containing yield returns a Generator.