PHPArray Functions

Array Functions

PHP ships with well over a hundred built-in array functions, which is both a strength and a source of overwhelm. Rather than trying to memorize the entire list, it helps to learn the handful that come up constantly, understand their sharp edges, and know that the rest are there when a specific need arises. This page tours the array functions you will reach for most often.

Combining arrays: array_merge() versus +

Both array_merge() and the + operator combine two arrays, but they disagree about what happens when the same key appears in both - and this difference is one of the most common sources of bugs when working with associative arrays.

Key collisions: merge keeps the last, + keeps the first

PHP
<?php
$defaults = ["theme" => "light", "retries" => 3];
$overrides = ["theme" => "dark"];

$merged = array_merge($defaults, $overrides);
print_r($merged); // "theme" from $overrides wins - last one in wins

$combined = $defaults + $overrides;
print_r($combined); // "theme" from $defaults wins - first one in wins
Array
(
    [theme] => dark
    [retries] => 3
)
Array
(
    [theme] => light
    [retries] => 3
)
array_merge() renumbers integer keys
For **integer-keyed** arrays, `array_merge()` does not treat the keys as significant - it renumbers everything sequentially, so `array_merge([5 => "a"], [9 => "b"])` produces keys `0` and `1`, not `5` and `9`. If you need to preserve numeric keys exactly, use `+` instead, which keeps original keys from both sides (favoring the left-hand array on collision).
array_keys() and array_values()

array_keys() returns a new indexed array of just the keys; array_values() returns a new indexed array of just the values, discarding whatever keys were there before. Both are useful whenever you need to hand off "just the labels" or "just the data" to another function.

Splitting keys from values

PHP
<?php
$inventory = ["pens" => 40, "notebooks" => 12, "staplers" => 5];

print_r(array_keys($inventory));
print_r(array_values($inventory));

// array_keys() also accepts a search value to find only matching keys
print_r(array_keys(["a" => 1, "b" => 2, "c" => 1], 1));
Array
(
    [0] => pens
    [1] => notebooks
    [2] => staplers
)
Array
(
    [0] => 40
    [1] => 12
    [2] => 5
)
Array
(
    [0] => a
    [1] => c
)
Finding values: in_array() and array_search()

in_array() answers a yes/no question - "is this value present anywhere in the array?" array_search() answers a "where" question - it returns the matching key, or false if nothing matched. Both default to loose comparison (==), so passing true as the third argument to switch on strict comparison (===) is worth doing whenever type matters, such as distinguishing 0 from "0" or false.

Loose versus strict search

PHP
<?php
$codes = ["0", "off", "no"];

var_dump(in_array(0, $codes));         // bool(true)  - "0" == 0 loosely
var_dump(in_array(0, $codes, true));   // bool(false) - "0" !== 0 strictly

var_dump(array_search("off", $codes)); // int(1)
bool(true)
bool(false)
int(1)
Extracting and removing pieces: array_slice() and array_splice()

array_slice() reads a portion of an array and returns it as a new array, leaving the original untouched. array_splice() does the opposite in spirit - it mutates the original array in place, removing (and optionally replacing) a portion of it, and returns the removed elements.

Read-only slice vs mutating splice

PHP
<?php
$letters = ["a", "b", "c", "d", "e"];

$middle = array_slice($letters, 1, 3); // read b, c, d - original unchanged
print_r($middle);
print_r($letters);

$removed = array_splice($letters, 1, 2, ["X", "Y", "Z"]); // replace b, c
print_r($removed);
print_r($letters); // $letters is now mutated
Array
(
    [0] => b
    [1] => c
    [2] => d
)
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
)
Array
(
    [0] => b
    [1] => c
)
Array
(
    [0] => a
    [1] => X
    [2] => Y
    [3] => Z
    [4] => d
    [5] => e
)

Function

Mutates original?

Typical use

array_merge()

No

Combine arrays, later keys win on collision

  • (union operator)

No

Combine arrays, earlier keys win on collision

array_keys()

No

Get all keys, or keys matching a value

array_values()

No

Re-index and get all values

in_array()

No

Check if a value exists (yes/no)

array_search()

No

Find the key of a matching value

array_slice()

No

Read a portion of an array

array_splice()

Yes

Remove and/or replace a portion in place

  • array_unique() removes duplicate values, comparing loosely by default.

  • array_reverse() returns a new array with element order flipped; pass true to preserve original keys.

  • array_flip() swaps every key with its value - useful for quickly checking "is this value one of my valid options" via isset().

  • array_sum() and array_product() total or multiply all numeric values in one call.

Most array functions do not mutate
The majority of PHP's array functions return a **new** array rather than modifying the one you passed in. `array_splice()`, `sort()`, and `array_walk()` are the notable exceptions that mutate by reference - check the return type in the manual whenever you are unsure.
Tip
When you catch yourself reaching for `array_merge()` on arrays that are keyed by IDs or other meaningful identifiers, stop and consider whether `+` is what you actually want - it is easy to accidentally lose data to `array_merge()`'s "last one wins" renumbering behavior.