Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 147 ยท Arrays

Array Functions

A practical tour of PHP array functions - push, pop, shift, array_merge versus +, slice and splice, strict in_array and array_search, unique, flip, fill, range and more.

PHP ships with about 80 functions whose names start with array_, plus a few classics like count(), in_array() and range(). You don't need to memorize them all, but knowing the main families saves you from writing loops that the language already provides, faster and better tested.

This lesson tours the functions you'll reach for every week, grouped by job: adding and removing at the ends, combining arrays, slicing, searching, working with keys, removing duplicates, building arrays and comparing them as sets. Along the way you'll learn the details that cause real bugs: which functions re-index keys, which modify the array in place, and why in_array() needs its third argument. Sorting gets its own lesson (Sorting Arrays), and so do the callback-based functions array_map, array_filter and array_reduce (the lesson after that).

Reading function signatures

The manual writes signatures like this:

PHP
array_push(array &$array, mixed ...$values): int
array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false): array

The & before $array means the function modifies your array in place (it's passed by reference), so you must pass a variable, not a literal or a function result. Functions without & leave the original alone and return a new array, which you need to store. Mixing the two up is the most common array bug, so watch for the & in each section below. Using Built-in Functions explains the notation in more detail.

Adding and removing at the ends

Four functions treat an array as a stack or a queue:

Function Does Returns
array_push($a, ...$values) Adds to the end The new count
array_pop($a) Removes the last element That element (or null if empty)
array_unshift($a, ...$values) Adds to the start The new count
array_shift($a) Removes the first element That element (or null if empty)

All four modify the array in place. array_shift() and array_unshift() also re-number integer keys from 0 (string keys are kept).

PHP Stacks and queues

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

For a single value, $array[] = $value is shorter and slightly faster than array_push(). array_shift() has to re-number every remaining key, so on very large queues the SPL's SplQueue (Iterators and the SPL) is more efficient.

Combining arrays: array_merge, + and spread

There are three ways to put arrays together, and they treat keys differently:

  • array_merge($a, $b): integer keys are re-numbered and appended; for duplicate string keys, the later value wins.
  • $a + $b (the union operator): keeps everything from $a and adds only the keys of $b that $a doesn't have. For duplicates, the left value wins, whether the key is an int or a string.
  • [...$a, ...$b] (spread): behaves like array_merge(). String keys in a spread work since PHP 8.1.
PHP array_merge versus the + operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The two patterns to remember:

  • Settings with defaults: $options + $defaults (user values win, defaults fill the gaps) or array_merge($defaults, $options). For string keys, both give the same values (only the key order can differ).
  • Joining lists: array_merge() or spread, never +, which silently drops elements whose index already exists.

array_combine($keys, $values) builds an associative array from two lists of the same length: array_combine(['a', 'b'], [1, 2]) gives ['a' => 1, 'b' => 2].

Slicing and splicing

array_slice($array, $offset, $length) returns a portion and leaves the original alone. A negative offset counts from the end. Integer keys are re-numbered unless you pass true as the fourth argument; string keys are always kept.

array_splice(&$array, $offset, $length, $replacement) modifies the array: it removes a portion, optionally inserts replacements, re-numbers integer keys, and returns what it removed. It's the tool for removing from the middle without leaving a gap.

PHP array_slice and array_splice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

array_slice() is also how you paginate an array: page $page with $perPage items is array_slice($items, ($page - 1) * $perPage, $perPage). To split a whole array into pages at once, use array_chunk($items, $perPage).

Searching: in_array and array_search

in_array($needle, $haystack) tells you whether a value is present. array_search($needle, $haystack) returns its key, or false. Both compare loosely (==) by default, and PHP's loose comparison has surprises even in PHP 8:

PHP Why searches should be strict

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Two rules prevent almost every search bug:

  1. Pass true as the third argument of in_array() and array_search(), so the type must match too (===). Loose matching on user input is how '0', '' and null slip through checks.
  2. Compare array_search()'s result with !== false, because a match at key 0 (or key '') is falsy.

To find all keys that hold a value, use array_keys($array, $value, true). Since PHP 8.4, array_find() and array_find_key() search with a callback instead of a fixed value; they're covered in array_map, array_filter and array_reduce.

in_array() checks every element one by one, which is slow for big arrays searched many times. If you need many membership checks, flip the list into keys once and use isset(): $allowed = array_flip($list); then isset($allowed[$value]) is a constant-time lookup.

Keys and values

Function Returns
array_keys($a) A list of the keys
array_values($a) A list of the values (re-indexed from 0)
array_flip($a) Keys and values swapped; duplicate values keep the last key
array_key_exists($k, $a) Whether the key exists (even with a null value)
array_key_first($a) / array_key_last($a) The first/last key, or null for an empty array
array_count_values($a) How many times each value occurs
PHP Working with keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

array_flip() only works when every value is an int or a string, since values become keys. Other values are skipped with a warning.

Removing duplicates

array_unique($array) removes duplicate values and keeps the first occurrence, with its original key. By default it compares values as strings ((string) $a === (string) $b), so 1, '1' and 1.0 all count as the same value.

PHP array_unique keeps first keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The gaps in the keys are a frequent surprise when the result is later sent as JSON: json_encode() turns an array with keys 0, 1, 3 into an object {"0":"php","1":"web","3":"api"}, not a list. Wrap the result in array_values() whenever you need a clean list.

Building arrays: range, array_fill and friends

PHP Generating arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

range() builds every element in memory at once. For a loop over a million numbers, a plain for loop or a generator (Generators) uses far less memory.

Comparing arrays as sets

The array_diff and array_intersect families compare arrays like sets. They keep the keys of the first array:

  • array_diff($a, $b): values of $a that are not in $b.
  • array_intersect($a, $b): values of $a that are also in $b.
  • array_diff_key() / array_intersect_key(): the same, comparing keys instead of values.
PHP Differences and intersections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

array_intersect_key() with a flipped whitelist is a neat way to keep only the fields you expect from user input, a habit that prevents "mass assignment" bugs.

All the diff and intersect variants

array_diff() and array_intersect() have a surprisingly large family. The names follow a simple code, so you can work out any of them without memorizing the list:

Part of the name Meaning
diff / intersect keep what is not in / is in the other arrays
_key compare keys only, values are ignored
_assoc the key and the value must both match
u before diff/intersect (as in array_udiff) compare values with your callback
_ukey compare keys with your callback
_uassoc values compared by PHP, keys by your callback
_u...assoc (as in array_udiff_uassoc) two callbacks: values first, then keys

The plain functions compare values as strings ((string) $a === (string) $b), which is why they cannot handle nested arrays or objects. A callback lets you decide what "equal" means. It receives two elements and must return a negative number, 0 or a positive number, exactly like a sort comparison, and 0 means "equal". That is why built-ins such as strcasecmp and strnatcmp work directly.

PHP Comparing with callbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Two cautions. The callback must be consistent: return 0 only for values you consider equal, otherwise results become unpredictable. And these functions take a callback as the last argument (two callbacks for the u...uassoc pair), after all the arrays, which trips people up when they pass several arrays. For huge arrays, a hand-built lookup with array_flip() and isset() is much faster than any array_diff family member, which works in O(nยทm) for the callback versions.

compact and extract: handle with care

compact('name', 'age') builds ['name' => $name, 'age' => $age] from variables, and extract($array) does the opposite, creating a variable for every key. compact() is harmless and sometimes used to pass data to templates. extract() is dangerous on untrusted data: extract($_GET) lets a visitor create or overwrite any variable in your script, the same hole the long-removed register_globals setting opened. Avoid extract(), and never use it on input.

PHP
$isAdmin = false;
extract($_GET);   // a request with ?isAdmin=1 now sets $isAdmin to '1'

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does array_merge(['a' => 1, 5 => 'x'], ['a' => 2, 5 => 'y']) return?

    array_merge re-numbers integer keys (so both 5s become 0 and 1) and lets later values win for string keys.
  2. 2. What does ['a', 'b'] + ['c', 'd', 'e'] return?

    The union operator keeps the left array and only adds keys it doesn't have. Keys 0 and 1 exist on the left, so only key 2 ('e') is added.
  3. 3. Why is if (!array_search('x', $list)) a bug?

    array_search returns the key or false. Key 0 (or '') is falsy, so always compare the result with !== false.
  4. 4. What does in_array('1e1', ['10']) return without the strict flag?

    Both are numeric strings, so loose comparison compares them as numbers, and 1e1 equals 10. Pass true as the third argument to compare types and values strictly.
  5. 5. Which function removes elements from the middle of an array and closes the gap?

    array_splice modifies the array in place and re-numbers integer keys. array_slice only returns a copy of a portion, and unset leaves a gap.

Summary

  • Watch the & in signatures: array_push/pop/shift/unshift/splice modify the array in place; most others return a new array.
  • array_merge() re-numbers integer keys and lets later string keys win; + keeps the left side's keys; [...$a, ...$b] acts like array_merge().
  • array_slice() returns a portion; array_splice() removes or inserts in place; array_chunk() splits into pages.
  • Always search strictly: in_array($v, $a, true), array_search($v, $a, true) !== false; flip to keys for fast repeated lookups.
  • array_keys(), array_values(), array_flip(), array_count_values() and array_key_first()/last() work with keys and values.
  • array_unique() keeps first occurrences with their original keys; re-index with array_values() before json_encode().
  • range(), array_fill(), array_fill_keys() and array_pad() build arrays; array_diff() and array_intersect() compare them as sets.
  • Never call extract() on user input.

Next: Sorting Arrays, where you'll sort by value, by key and with your own comparison rules.