PHP arrays

One type for lists and maps, the array functions worth knowing, and array_map/filter across collections.

Lists and associative arrays

$list = [1, 2, 3];                      // indexed
$user = ["id" => 7, "name" => "Ada"];   // associative

$list[] = 4;                            // append
echo $user["name"];
echo $list[0] ?? "missing";             // null-coalescing for missing keys

$id = 7;
$h = "id";
echo $user[$h];                         // variable key

One array type serves both roles because PHP arrays are ordered maps. Iteration preserves insertion order.

Array functions worth knowing

FunctionResult
countNumber of elements
array_mapTransform every element
array_filterKeep elements passing a test
array_reduceCollapse to one value
in_array / array_key_existsMembership tests
array_merge / +Combine arrays
sort / usortSort by value / by callback
array_columnPluck one field from rows
$adults = array_filter($people, fn($p) => $p["age"] >= 18);
$names  = array_map(fn($p) => $p["name"], $adults);
$total  = array_reduce($items, fn($sum, $i) => $sum + $i["price"], 0);

usort($people, fn($a, $b) => $a["age"] <=> $b["age"]);
$ids = array_column($people, "id");
💡
array_filter preserves keys, so the result may not be a sequential list. Wrap with array_values() before sending JSON.

Arrays and JSON

$json = json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
$back = json_decode($json, true);       // true = associative arrays

if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException(json_last_error_msg());
}

FAQ

array_map or foreach?
Functional functions read better for simple transforms and pipelines. Use foreach when you need to modify in place or keep state across iterations.
How do I check if a key exists?
array_key_exists($k, $a) is true even for null values; isset($a[$k]) is not. Choose based on whether null is a meaningful value.

PHP variables and strings Forms, sessions and safety

Last refreshed 2026-09-17.