Working with Arrays in PHP
PHP has one array type, and it does two jobs at once. It is a list when its keys are consecutive integers starting at zero, and it is a dictionary when its keys are strings. Both jobs are served by the same data structure, the same functions, and the same syntax, which is why a PHP array is usually described as an ordered map. That description is the key to the whole chapter: an array is not a sequence with a fixed shape, it is a collection of key and value pairs where the keys have an order of their own and where you decide which of the two jobs you want at the moment you build it. By the end of this chapter you will be able to pick the right shape for a problem, choose between the imperative and the functional style deliberately, and know exactly which of the standard functions copy, which of them modify in place, and which of them preserve the keys.
An array literal uses square brackets. With consecutive integer keys it is a list.
<?php
$fruits = ['apple', 'banana', 'cherry'];
echo $fruits[0]; // apple
With string keys it is a dictionary.
<?php
$prices = ['apple' => 1.50, 'banana' => 0.80, 'cherry' => 3.25];
echo $prices['banana']; // 0.80
The two forms can be mixed in one array, and the key type is decided per element. This flexibility is convenient and it is also the source of most array bugs in PHP, because the same code has to handle both shapes.
<?php
$mixed = [0 => 'first', 'name' => 'Ada', 5 => 'sixth'];
PHP 8.1 added array_is_list, which answers the question directly.
<?php
var_dump(array_is_list([1, 2, 3])); // true
var_dump(array_is_list([1 => 'a', 2 => 'b'])); // false, keys are not consecutive from zero
var_dump(array_is_list(['a' => 1])); // false
A key is either an int or a string. Nothing else is allowed, and PHP converts as needed: a key that looks like a decimal integer becomes an integer key, and everything else becomes a string key.
<?php
$a = ['10' => 'ten'];
var_dump(array_keys($a)); // array(1) { [0]=> int(10) }
Three rules cause nearly all of the confusion.
Integer keys are renumbered when the array is built. Only literal integer keys written in the source keep their value; computed keys do not.
<?php
$a = [1, 2, 3];
$b = [1 => 'a', 2 => 'b'];
var_dump(array_keys($b)); // array(2) { [0]=> int(1) [1]=> int(2) }
A string key that looks like an integer is converted to an integer key. "10" and 10 are the same key.
A float key is truncated to an integer. A bool key becomes 1 or 0. An array or an object key is a fatal error, because it cannot be represented.
Assigning to a key that already exists replaces the value and keeps the position.
<?php
$config = ['debug' => false, 'env' => 'prod'];
$config['debug'] = true;
var_dump($config); // 'debug' is still first
count gives the number of elements, and sizeof is an alias of it.
<?php
$fruits = ['apple', 'banana'];
echo count($fruits); // 2
Reading a missing key emits a warning and yields null.
<?php
$fruits = ['apple'];
echo $fruits['pear']; // Warning: Undefined array key "pear"
isset answers whether a key exists and is not null.
<?php
$data = ['name' => 'Ada', 'nickname' => null];
var_dump(isset($data['name'])); // true
var_dump(isset($data['nickname'])); // false, the value is null
var_dump(isset($data['missing'])); // false
array_key_exists answers whether the key exists, regardless of the value.
<?php
var_dump(array_key_exists('nickname', $data)); // true
var_dump(array_key_exists('missing', $data)); // false
The difference between the two is the whole point of having both: a key that exists with a null value is invisible to isset but visible to array_key_exists. When you are checking for the presence of a field, use array_key_exists.
The null coalescing operator is the shortest safe read.
<?php
$name = $data['name'] ?? 'anonymous';
$city = $data['city'] ?? 'unknown'; // no warning, the key may be absent
foreach is the loop that walks an array, and it comes in two useful forms.
<?php
$prices = ['apple' => 1.50, 'banana' => 0.80];
foreach ($prices as $fruit) {
echo $fruit, "\n"; // 1.50, then 0.80
}
foreach ($prices as $fruit => $price) {
echo "$fruit: $price\n";
}
The loop variable is a copy by default, so changing it does not change the array.
<?php
$numbers = [1, 2, 3];
foreach ($numbers as $n) {
$n *= 2;
}
var_dump($numbers); // still array(1) { [0]=> int(1) ... }
To modify the array in place, take the value by reference with an ampersand.
<?php
$numbers = [1, 2, 3];
foreach ($numbers as $n) {
$n *= 2;
}
var_dump($numbers); // unchanged
foreach ($numbers as &$n) {
$n *= 2;
}
unset($n); // break the reference, see below
var_dump($numbers); // array(3) { [0]=> int(2) [1]=> int(4) [2]=> int(6) }
The unset after the loop is not optional politeness. After a foreach by reference, the loop variable remains a reference to the last element, and any later assignment to that variable writes into the array. This is the classic PHP bug where a function mysteriously modifies an array it was only supposed to read.
<?php
function doubleAll(array $items): array
{
foreach ($items as &$item) {
$item *= 2;
}
unset($item); // without this, $item still points at the last element
return $items;
}
array_walk applies a callback to every element and can modify the array in place.
<?php
$totals = ['a' => 1, 'b' => 2];
array_walk($totals, function (&$value, $key) {
$value = $value * 10;
});
var_dump($totals); // a => 10, b => 20
PHP has a family of functions that take an array and a callback and return a new array. They are the counterpart of foreach, and they compose.
array_map applies a callback to every element. With a single array the keys are preserved; with several arrays the callback receives one argument per array and the result is renumbered from zero.
<?php
$prices = ['apple' => 1.50, 'banana' => 0.80];
$withTax = array_map(fn (float $p) => $p * 1.2, $prices);
var_dump($withTax); // same keys, new values
$names = ['Ada', 'Grace'];
$ages = [36, 45];
$pairs = array_map(fn (string $n, int $a) => "$n ($a)", $names, $ages);
var_dump($pairs); // array(2) { [0]=> string(8) "Ada (36)" ... }
array_filter keeps the elements for which the callback returns a truthy value, and it preserves the keys.
<?php
$numbers = [1, 2, 3, 4, 5, 6];
$evens = array_filter($numbers, fn ($n) => $n % 2 === 0);
var_dump($evens); // array(3) { [1]=> int(2) [3]=> int(4) [5]=> int(6) }
With no callback, array_filter removes every falsy value, which is occasionally what you want and frequently a surprise.
<?php
$clean = array_filter([1, 0, null, '', 'x']);
var_dump($clean); // array(1) { [4]=> string(1) "x" }
array_reduce folds an array into a single value.
<?php
$total = array_reduce([10, 20, 30], fn ($carry, $n) => $carry + $n, 0);
var_dump($total); // int(60)
The third argument is the initial value, and it is what makes the fold well defined for an empty array.
<?php
$empty = array_reduce([], fn ($carry, $n) => $carry + $n, 0);
var_dump($empty); // int(0), not null
array_keys and array_values convert between the two shapes of an array.
<?php
$prices = ['apple' => 1.50, 'banana' => 0.80];
var_dump(array_values($prices)); // a plain list
var_dump(array_keys($prices)); // ['apple', 'banana']
array_column is the function that turns a list of records into a lookup table, and it is used constantly.
<?php
$rows = [
['id' => 1, 'name' => 'Ada', 'role' => 'admin'],
['id' => 2, 'name' => 'Grace', 'role' => 'editor'],
];
$byId = array_column($rows, null, 'id');
var_dump($byId[2]['name']); // Grace
$names = array_column($rows, 'name');
var_dump($names); // ['Ada', 'Grace']
The three-argument form, array_column($rows, 'name', 'id'), builds a map from the third argument to the second.
The square bracket with no key appends to the end of the array.
<?php
$stack = [];
$stack[] = 'first';
$stack[] = 'second';
var_dump($stack); // [0] => 'first', [1] => 'second'
array_push and array_pop work at the end of the array.
<?php
$stack = ['a'];
array_push($stack, 'b', 'c');
var_dump($stack); // a, b, c
$last = array_pop($stack);
var_dump($last, $stack); // 'c', and a, b
array_unshift and array_shift work at the front.
<?php
$queue = ['b', 'c'];
array_unshift($queue, 'a');
var_dump($queue); // a, b, c
$first = array_shift($queue);
var_dump($first, $queue); // 'a', and b, c
array_shift and array_pop reindex the remaining integer keys, so the array stays a list.
Removing a specific key is done with unset.
<?php
$data = ['a' => 1, 'b' => 2, 'c' => 3];
unset($data['b']);
var_dump($data); // a and c only, keys preserved
array_splice removes elements from the array and optionally replaces them, modifying the original in place and returning what was removed.
<?php
$letters = ['a', 'b', 'c', 'd', 'e'];
$removed = array_splice($letters, 1, 2, ['X']);
var_dump($removed); // ['b', 'c']
var_dump($letters); // a, X, d, e
array_slice is the non-destructive counterpart: it returns a portion and leaves the original alone.
<?php
$letters = ['a', 'b', 'c', 'd', 'e'];
var_dump(array_slice($letters, 1, 2)); // b, c
var_dump(array_slice($letters, -2)); // d, e, a negative offset counts from the end
var_dump(array_slice($letters, 0, 2, true)); // keys preserved
array_merge concatenates arrays. Integer keys are renumbered from zero; string keys from the later array overwrite the earlier ones.
<?php
var_dump(array_merge([1, 2], [3, 4])); // 1, 2, 3, 4
var_dump(array_merge(['x' => 1], ['x' => 2])); // ['x' => 2]
array_merge_recursive turns conflicting string keys into arrays rather than overwriting.
<?php
var_dump(array_merge_recursive(['x' => 1], ['x' => 2]));
// array(1) { ["x"]=> array(2) { [0]=> int(1) [1]=> int(2) } }
The spread operator does the same job inside an array literal, and it is the form to prefer in new code because it reads better.
<?php
$a = ['apple'];
$b = ['banana'];
$all = [...$a, ...$b];
var_dump($all); // apple, banana
Since PHP 8.1 the spread operator also accepts string keys, which array_merge has always supported but the literal syntax did not.
<?php
$merged = [...['a' => 1], ...['b' => 2]];
var_dump($merged); // a => 1, b => 2
array_combine builds an array from two arrays, one of keys and one of values.
<?php
$ids = [101, 102, 103];
$labels = ['alpha', 'beta', 'gamma'];
$map = array_combine($ids, $labels);
var_dump($map[102]); // beta
in_array answers whether a value is present.
<?php
var_dump(in_array('1', [1, 2, 3])); // true, loose comparison
var_dump(in_array('1', [1, 2, 3], true)); // false, strict comparison
Always pass the third argument true unless you specifically want loose comparison. The loose form still treats the string "1" and the integer 1 as equal, and it compares a number against a numeric-looking string numerically rather than as text.
<?php
var_dump("1" == 1); // true
var_dump("1" === 1); // false
var_dump("abc" == 0); // false since PHP 8
var_dump("1abc" == 1); // false since PHP 8
The last two results are the PHP 8 change: when a number is compared with a string that does not look like a number, the number is converted to a string instead of the other way round, so 0 == "abc" is no longer true.
array_search returns the key of the first match, or false if there is none.
<?php
$prices = ['apple' => 1.50, 'banana' => 0.80];
$key = array_search(0.80, $prices);
var_dump($key); // string(6) "banana"
var_dump(array_search(9.99, $prices)); // false
Because the failure value is false and 0 is a valid key, a correct check tests against false explicitly rather than against a falsy value.
<?php
if (array_search(0.80, $prices) !== false) {
echo "found";
}
array_flip swaps keys and values. It is the fastest way to build a lookup set.
<?php
$names = ['apple', 'banana'];
$set = array_flip($names);
var_dump($set['banana']); // int(1), the original index
array_unique removes duplicate values and keeps the first occurrence, preserving the original keys.
<?php
$tags = ['php', 'web', 'php', 'api'];
var_dump(array_unique($tags));
// array(3) { [0]=> string(3) "php" [1]=> string(3) "web" [3]=> string(3) "api" }
By default the comparison is string based. Pass SORT_STRING or SORT_REGULAR to be explicit about the intended semantics, and the difference matters when the values look alike.
<?php
var_dump(array_unique([1, '01', 1.0], SORT_REGULAR)); // one element, they compare numerically
var_dump(array_unique([1, '01', 1.0], SORT_STRING)); // two elements, "1" and "01" differ as text
PHP has two families of sorting functions, and the difference between them is what happens to the keys.
The first family discards the keys and produces a list.
<?php
$letters = ['c', 'a', 'b'];
sort($letters); // ascending
var_dump($letters); // a, b, c
rsort($letters); // descending
var_dump($letters); // c, b, a
The second family keeps the keys, and the comparison is between the values.
<?php
$prices = ['apple' => 1.50, 'banana' => 0.80, 'cherry' => 3.25];
asort($prices); // ascending by value, keys preserved
var_dump($prices);
arsort($prices); // descending by value, keys preserved
The third family keeps the keys and sorts by the key.
<?php
$prices = ['apple' => 1.50, 'banana' => 0.80, 'cherry' => 3.25];
ksort($prices); // ascending by key
krsort($prices); // descending by key
When the built-in ordering is not the one you want, a fourth group takes a comparison callback.
<?php
$words = ['pear', 'a', 'banana'];
usort($words, fn (string $a, string $b) => strlen($a) <=> strlen($b));
var_dump($words); // a, pear, banana, sorted by length
usortsorts by value and discards the keys.uasortsorts by value and keeps the key and value pairs together.uksortsorts by key.
<?php
$prices = ['apple' => 1.50, 'banana' => 0.80, 'cherry' => 3.25];
uasort($prices, fn ($a, $b) => $a <=> $b);
var_dump($prices); // banana, apple, cherry, keys still attached
The callback returns an integer: negative when the first argument comes first, positive when the second does, and zero when they are equal. The spaceship operator a <=> b produces exactly that integer, and it is the idiomatic way to write the comparison.
When the sort should not disturb the original, asort and friends return a new array, while sort and friends modify the array in place. This is a genuine asymmetry between the two families that catches people out.
A list in PHP is simply an array whose keys are the integers zero through one less than its length. array_is_list tests for it.
Destructuring assigns the elements of an array to variables.
<?php
[$first, $second, $third] = ['a', 'b', 'c'];
var_dump($first, $second, $third); // a, b, c
Destructuring works with string keys too, and then the order of the variables does not matter.
<?php
['name' => $name, 'role' => $role] = ['name' => 'Ada', 'role' => 'admin'];
var_dump($name, $role); // Ada, admin
The list keyword is the older syntax for the same thing and is still seen in older code.
<?php
list($a, $b) = [1, 2];
Destructuring is not limited to two variables, and it works with nested arrays.
<?php
[$x, [$y, $z]] = [1, [2, 3]];
var_dump($x, $y, $z); // 1, 2, 3
The spread operator unpacks an array into an argument list or into a new array.
<?php
function sum(int ...$numbers): int
{
return array_sum($numbers);
}
echo sum(1, 2, 3); // 6
$merged = [...['a'], ...['b', 'c']];
var_dump($merged); // a, b, c
Assigning an array to another variable copies the array by value. The two variables are then independent.
<?php
$a = [1, 2];
$b = $a;
$b[0] = 99;
var_dump($a); // array(2) { [0]=> int(1) [1]=> int(2) }
var_dump($b); // array(2) { [0]=> int(99) [1]=> int(2) }
This is a copy of the structure, and it is cheap because PHP uses copy-on-write: the actual copy only happens if one of the two variables is modified.
When you want the two names to refer to the same array, use a reference.
<?php
$a = [1, 2];
$b = &$a;
$b[0] = 99;
var_dump($a); // array(2) { [0]=> int(99) [1]=> int(2) }
unset removes an element from an array.
<?php
$data = ['a' => 1, 'b' => 2];
unset($data['a']);
var_dump($data); // only b remains
unset on an array passed by reference removes the key from the caller’s array as well, which is why an unset inside a foreach by reference is a way to filter an array in place.
<?php
$items = [1, 2, 3, 4];
foreach ($items as $k => $v) {
if ($v % 2 === 0) {
unset($items[$k]);
}
}
var_dump($items); // 1, 3
| Mistake | What actually happens | Correction |
|---|---|---|
Modifying the loop variable in a plain foreach | Nothing happens to the array | Take the value by reference with & |
Forgetting unset after a foreach by reference | The loop variable stays bound to the last element and corrupts a later assignment | Add unset($value) at the end of the loop |
Using isset to test for a key that may hold null | It reports false for a key that exists | Use array_key_exists |
Checking array_search with a truthy test | The key 0 is treated as not found | Compare against false explicitly |
Using in_array without the strict flag | "1" matches 1, and other numeric-looking strings are compared numerically | Pass true as the third argument |
Using sort and expecting the keys to survive | The keys are discarded and renumbered | Use asort or uasort |
Using array_merge expecting string keys to be combined | The later value silently overwrites the earlier one | Use array_merge_recursive or the spread operator |
Expecting array_filter to renumber the keys | The original keys are preserved | Wrap the result in array_values |
| Reading a missing key directly | A warning is emitted and null is returned | Use ?? or check with array_key_exists |
| Assuming a function argument is a copy of an array | PHP copies by value, so it usually is one, but references and objects are shared | Pass arrays by value and return new ones |
The array chapter is the practical core of PHP. The next chapter takes the code you have been writing inside loops and turns it into reusable units: functions with declared parameter types, closures that capture their environment, and the callback conventions that make the array functions compose with your own code.
Approach:
The subject of this chapter is a data structure, but the skill being taught is choosing the right tool for the shape of the problem. PHP offers one array type, so the decision is never “which array”; it is “list or dictionary”, and it is “loop or pipeline”. Each of those choices has a default that is safe and a variant that is faster or clearer, and the defaults are not always the ones you want. The chapter therefore teaches the array as an ordered map first, so that every function in the standard library can be described in terms of what it does to the keys and the values, and then teaches the differences between the functional functions and the imperative loops, so that the choice between them is a deliberate one. Throughout, the practical question is kept in view: does this function copy the array, modify it in place, or preserve its keys?
Steps:
- Establish the underlying model. An array is an ordered map, so every operation is a question about keys and values. Write both shapes, note that integer keys are renumbered at construction and that a numeric string key becomes an integer key, and use
array_is_listto decide explicitly whether an array is a list. - Learn to read safely.
countfor the size,array_key_existsfor the presence of a key,issetfor the presence of a non-null value, and the null coalescing operator for a read with a default. Choosearray_key_existsoverissetwhenever the value is allowed to be null. - Learn both traversal styles.
foreachby value,foreachby reference with the trailingunset, andarray_walkfor an in-place mutation driven by a callback. - Move to the functional style, where the pipeline is the point:
array_mapfor a one-to-one transformation,array_filterfor a selection that preserves keys,array_reducefor a fold with an explicit initial value, andarray_columnfor turning a list of records into a lookup table. - Learn the mutating operations and mark them clearly in your own notes, because this is where the surprises live:
array_pushandarray_popat the end,array_unshiftandarray_shiftat the front,unsetfor a specific key,array_splicefor an in-place removal and replacement, andarray_slicefor a non-destructive copy. - Learn the combining operations, and pay attention to the key rules:
array_mergerenumbers integer keys and overwrites string keys,array_merge_recursivekeeps both values instead, and the spread operator does the same job inside a literal and, since PHP 8.1, accepts string keys. - Learn the search operations with their failure values:
in_arraywith the strict flag,array_searchreturning a key orfalse,array_flipfor a fast lookup set,array_uniquefor deduplication, andarray_keysandarray_valuesfor converting between the two shapes. - Learn the three sorting families as three different questions:
sortandrsortfor the values with the keys discarded,asortandarsortfor the values with the keys kept, andksortandkrsortfor the keys, plus the three callback formsusort,uasortanduksortfor a custom comparison written with the spaceship operator. - Learn the modern conveniences: destructuring with
[$a, $b] = $arrand with string keys, the spread operator, andlist()as the older spelling of the same idea. - Close with the semantics that explain the rest: assignment copies by value and copies lazily,
&makes two names refer to the same array, andunsetremoves a key from the caller’s array when the array was passed by reference.
Answer:
After this chapter, an array problem in PHP has a routine answer.
- Decide the shape first. A list when the keys are consecutive integers from zero, a dictionary when the keys are names, and
array_is_listwhen the distinction needs to be checked rather than assumed. - Read with
count,array_key_exists,issetand??, choosing the null-aware check whenever a key is allowed to holdnull. - Transform with
array_map, select witharray_filter, fold witharray_reduce, and reshape a list of records witharray_column. - Mutate at the ends with
array_push,array_pop,array_unshiftandarray_shift, remove a key withunset, cut and replace witharray_splice, and take a copy witharray_slice. - Combine with
array_mergewhen integer keys may be renumbered, witharray_merge_recursiveor the spread operator when string keys must survive, and witharray_combinewhen one array supplies the keys. - Search with
in_arrayin strict mode,array_searchcompared againstfalse,array_flipfor a lookup set andarray_uniquefor deduplication. - Sort with
sortwhen the keys may go,asortwhen they must stay with the values,ksortwhen the keys decide the order, andusort,uasortoruksortwhen a custom comparison is needed. - Read and write elements with destructuring, unpack with the spread operator, and remember that assignment copies while
&shares.
That is the whole surface of PHP arrays, and it is enough to write the data-handling code that the object-oriented chapter then organises into classes.
