PHP arrays are ordered maps: integer lists and string keys in one structure. Prefer foreach, array_map, and array_filter over C-style for when transforming. ?? reads a default when the key is missing or null; isset is false for null; array_key_exists sees null values.
This PHP cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- List:
$n = [10, 20];append$n[] = 30. - Map:
$user = ["id" => 1, "email" => "a@b.c"]; - foreach:
foreach ($rows as $i => $row)—$rowis a copy unless&$row. - map/filter:
array_map(fn ($x) => $x * 2, $n),array_filter($n, fn ($x) => $x > 0). - keys:
array_keys,array_values,in_array(..., true)for strict. - ?? vs isset:
$a["x"] ?? 0.issetis false if the value is null. - spread:
[...$a, ...$b]in PHP 7.4+ for lists;array_mergefor string keys. - count:
count($arr). Empty array is notnull— check=== []if needed.
Copy-paste examples
Map, filter, and a safe getter
Use strict in_array. Arrow functions need PHP 7.4+.
<?php
function paidTotal(array $orders): int
{
$paid = array_filter($orders, fn (array $o): bool => !empty($o['paid']));
$amounts = array_map(fn (array $o): int => (int) $o['total'], $paid);
return array_sum($amounts);
}
function pick(array $row, string $key, mixed $default = null): mixed
{
return array_key_exists($key, $row) ? $row[$key] : $default;
}Common mistakes
- Foreach by reference then reusing the
$valuevariable after the loop (PHP leftover reference bug). in_array(0, ["foo"])withouttrue— loose compare surprises.- Confusing
array_mergereindexing numeric keys with+union. - Using
empty($arr["k"])when"0"is a valid value.
FAQ
- Array or object? Arrays for JSON-like data and config. Classes for behavior.
json_decode($s, true)gives arrays.
- Does PHP have list comprehensions? No. Use
array_map/array_filteror aforeachthat builds a new array.
- How do I unique a list?
array_values(array_unique($n, SORT_REGULAR))and know that unique is loose unless you handle it yourself.
Related PHP cheat sheets
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds custom web development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.