iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Array Functions

Quick reference to the most-used array functions in PHP. Search the manual for the rest — there are about 80 in total.

Inspect

FunctionReturns
count($arr)Number of elements.
array_keys($arr) / array_values($arr)Keys / values.
array_key_exists($k, $arr)True even for null values.
in_array($v, $arr, strict: true)Membership.
array_search($v, $arr, strict: true)First key with that value, or false.
array_is_list($arr)True if 0-indexed with no gaps (8.1+).

Transform

FunctionDoes
array_map($fn, $arr)Apply fn to every value.
array_filter($arr, $fn)Keep elements where fn is truthy.
array_reduce($arr, $fn, $initial)Fold to a single value.
array_column($arr, 'col')Pluck a column.
array_flip($arr)Swap keys ↔ values.
array_unique($arr)Dedup, preserve first occurrence.
array_reverse($arr)Reverse order.
array_chunk($arr, $n)Split into N-sized arrays.

Combine

FunctionDoes
array_merge($a, $b)Concat; string keys overwrite.
array_combine($k, $v)Pairs into dict.
array_diff($a, $b)Elements in a, not in b.
array_intersect($a, $b)Elements in both.

Modify

FunctionDoes
array_push($arr, $v) / $arr[] = $vAppend.
array_pop($arr)Remove and return last.
array_shift / array_unshiftFront of array.
array_splice($arr, $offset, $len, $replace)Remove + insert in one go.
array_slice($arr, $offset, $len)Read a slice (non-destructive).

Sort

sort rsort asort arsort ksort krsort usort uksort uasort natsort — all sort in place.

Tip: Most array functions accept a callable. With arrow functions (fn($x) => ...), the resulting code reads almost like the functional equivalent in JavaScript or Python.

Example

Example
<?php
$a = [3, 1, 4, 1, 5, 9];
echo count($a), PHP_EOL;
echo array_sum($a), PHP_EOL;
print_r(array_unique($a));
print_r(array_map(fn($n) => $n * 2, $a));
print_r(array_filter($a, fn($n) => $n > 2));
Try it Yourself »

Exercise

Count occurrences of each value.

($words)

Test yourself

Q1. Pluck a column with…
Q2. in_array safer flag is…
Q3. array_unique preserves…

Discussion

Loading…