PHP Array Functions: The Ultimate Cheat Sheet
Arrays are the backbone of data manipulation in PHP. Whether you’re building a simple script or a complex Laravel application, mastering PHP’s built‑in array functions can dramatically improve code readability, performance, and maintainability. This cheat sheet gathers the most commonly used functions, grouped by purpose, complete with short explanations and ready‑to‑copy code snippets.
Table of Contents
- Basic Array Functions
- Sorting Functions
- Searching & Retrieval
- Manipulation (Add / Remove)
- Filtering, Mapping & Reducing
- Merging & Splitting
- Iteration Helpers
- Best Practices & Common Pitfalls
Basic Array Functions
Creating & Counting
array() – The literal way to create an array.
$numbers = array(1, 2, 3, 4); // or $numbers = [1,2,3,4];
count() – Returns the number of elements.
echo count($numbers); // 4
Checking Types & Existence
is_array() – Verifies a variable is an array.
if (is_array($data)) { /* … */ }
array_key_exists() – Checks if a specific key is present.
if (array_key_exists('name', $user)) { /* … */ }
Extracting Keys & Values
array_keys() – Returns all keys.
$keys = array_keys($user);
array_values() – Returns all values, re‑indexing numerically.
$values = array_values($user);
Sorting Functions
Simple Sorting
sort() – Sorts an array in ascending order and re‑indexes numeric keys.
$arr = [3,1,4]; sort($arr); // [1,3,4]
rsort() – Same as sort() but descending.
Associative Sorting
asort() – Sorts by values while preserving key association.
$scores = ['Alice'=>90,'Bob'=>75]; asort($scores); // Alice => 90, Bob => 75
ksort() – Sorts by keys.
User‑Defined Sorting
usort() – Sorts using a custom callback.
usort($arr, function($a,$b){ return $a['age'] <=> $b['age']; });
Similar functions exist for keys: uksort(), uasort().
Searching & Retrieval
Value Search
in_array() – Checks if a value exists.
if (in_array('PHP', $languages)) { /* … */ }
array_search() – Returns the key of the first matching value.
$key = array_search('Bob', $names); // e.g., 2
Key Search
array_key_first() and array_key_last() – Retrieve the first or last key.
Finding Duplicates
array_unique() – Removes duplicate values.
$unique = array_unique([1,2,2,3]); // [1,2,3]
Manipulation (Add / Remove)
Adding Elements
array_push() – Append one or more values.
array_push($stack, 'new'); // $stack[] = 'new';
array_unshift() – Prepend values.
Removing Elements
array_pop() – Removes the last element.
$last = array_pop($stack);
array_shift() – Removes the first element.
Splicing & Slicing
array_slice() – Returns a portion of the array without altering the original.
$part = array_slice($arr, 2, 3); // from index 2, length 3
array_splice() – Removes/replaces a portion **and** modifies the original array.
array_splice($arr, 1, 2, ['a','b']); // replace 2 items starting at index 1
Filtering, Mapping & Reducing
Filtering
array_filter() – Returns elements that pass a callback test.
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);
Mapping
array_map() – Applies a callback to each element.
$squared = array_map(fn($n) => $n*$n, $numbers);
Reducing
array_reduce() – Reduces the array to a single value.
$sum = array_reduce($numbers, fn($carry,$item)=>$carry+$item, 0);
Column Extraction
array_column() – Pulls out a single column from a multi‑dimensional array.
$emails = array_column($users, 'email');
Merging & Splitting
Merging
array_merge() – Combines arrays, re‑indexing numeric keys.
$all = array_merge($arr1, $arr2);
array_merge_recursive() – Merges recursively, turning duplicate keys into arrays.
Union Operator
+ – Preserves keys from the left array.
$union = $arr1 + $arr2; // $arr1 keys win
Chunking
array_chunk() – Splits an array into smaller pieces.
$chunks = array_chunk($numbers, 3); // [[1,2,3],[4,5,6],…]
Iteration Helpers
Walking
array_walk() – Applies a user function to each element (by reference).
Walking with Keys
array_walk_recursive() – Works on multi‑dimensional arrays.
Extracting Sub‑arrays
array_intersect() – Returns common values.
array_diff() – Returns values in the first array not present in others.
Best Practices & Common Pitfalls
- Prefer native functions over loops. Functions like
array_mapandarray_filterare implemented in C and are faster. - Beware of key re‑indexing.
sort(),array_merge(), andarray_values()reset numeric keys – useasort()or the union operator if you need to keep them. - Immutable vs mutable. Functions ending with “_slice” return a new array, while “_splice” modifies the original. Choose based on whether you want side‑effects.
- Strict comparisons. Pass
trueas the third argument toin_array()for type‑safe checks. - Memory considerations. Large arrays combined with
array_merge()can double memory usage. Use generators oryieldfor very large data sets.
Quick Reference Table
| Category | Function | Description |
|---|---|---|
| Creation | array() |
Creates a new array. |
| Count | count() |
Returns element count. |
| Sorting | sort(), asort(), ksort(), usort() |
Various sorting mechanisms. |
| Search | in_array(), array_search() |
Find values or keys. |
| Add/Remove | array_push(), array_pop(), array_shift()
|