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
| Function | Returns |
|---|---|
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
| Function | Does |
|---|---|
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
| Function | Does |
|---|---|
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
| Function | Does |
|---|---|
array_push($arr, $v) / $arr[] = $v | Append. |
array_pop($arr) | Remove and return last. |
array_shift / array_unshift | Front 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)
snake_case; 18 chars.
Discussion
Loading…