Arrays are PHP's workhorse data structure: request data, query results and config all arrive as arrays.
A PHP array is an ordered map: every element has a key and a value, and insertion order is kept. The same type serves as a list and as a dictionary.
- List:
$colors = ['red', 'green'];gets keys 0 and 1. Append with$colors[] = 'blue';. - Associative:
$user = ['name' => 'Ada', 'age' => 36];. - Keys are ints or strings. A numeric string key such as
"7"is cast to the int7, andtruebecomes1.
Read with $user['name']. Reading a missing key gives a warning and null, so check first with isset($user['email']), array_key_exists('email', $user) or use $user['email'] ?? 'none'. Remove an element with unset($colors[0]); the remaining keys are not renumbered.
count($a) gives the size, in_array($x, $a, true) searches values (pass true for strict comparison), and array_keys and array_values split a map apart.
Destructuring unpacks arrays: [$first, $second] = $colors; or ['name' => $n] = $user;. The spread operator copies elements in: [...$a, ...$b], which also works with string keys since PHP 8.1.
Arrays are values: assigning or passing one gives an independent copy (PHP copies lazily, so this is cheap until you modify it).
Example
<?php
$colors = ['red', 'green'];
$colors[] = 'blue';
$user = ['name' => 'Ada', 'age' => 36];
foreach ($colors as $i => $c) echo "$i=$c "; // 0=red 1=green 2=blue
echo "\n";
echo $user['email'] ?? 'no email', "\n"; // no email
var_dump(isset($user['age'])); // bool(true)
[$first, , $third] = $colors;
echo "$first $third\n"; // red blue
$copy = $colors;
$copy[0] = 'pink';
echo $colors[0], "\n"; // red (arrays are values)
unset($colors[1]);
print_r(array_keys($colors)); // [0, 2]: keys are not renumberedRemember
- One array type is both list and ordered dictionary
- Use ?? or isset to read keys that may be missing
- Arrays are copied on assignment, unlike objects
Watch out for
- Expecting unset() to renumber a list; call array_values() if you need 0..n-1 keys again.