Arrays

PHP · Essentials · 12 min

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 int 7, and true becomes 1.

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 renumbered

Remember

  • 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.

Check yourself

  1. After $a = ['x' => 1]; $b = $a; $b['x'] = 2; what is $a['x']?
  2. What keys does ['5' => 'a', 'b'] have?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.php.net/manual/en/language.types.array.php

Arrays · PHP · Topolearn