Cheat Sheets

PHP Arrays & Functions Cheat Sheet: Map, Filter, Keys & Common Helpers

By ArpaNeuro Team September 22, 2026
PHP arrays cheat sheet

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)$row is 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. isset is false if the value is null.
  • spread: [...$a, ...$b] in PHP 7.4+ for lists; array_merge for string keys.
  • count: count($arr). Empty array is not null — 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 $value variable after the loop (PHP leftover reference bug).
  • in_array(0, ["foo"]) without true — loose compare surprises.
  • Confusing array_merge reindexing numeric keys with + union.
  • Using empty($arr["k"]) when "0" is a valid value.

FAQ

  1. Array or object? Arrays for JSON-like data and config. Classes for behavior. json_decode($s, true) gives arrays.
  1. Does PHP have list comprehensions? No. Use array_map/array_filter or a foreach that builds a new array.
  1. 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.

← All Articles Get a Quote →