Arrays are one of the most frequently used data types in PHP. Beyond the basics (adding/removing elements, iteration, sorting), PHP offers dozens of built-in array functions, which allow you to:
- transform data (mapping, filtering),
- combine and compare sets,
- extract columns from multidimensional arrays,
- work with keys and values,
- generate and fill arrays,
- randomly select elements.
Related earlier lessons: Sorting Arrays in PHP, Iterating Arrays, Basic Array Operations, Indexed/Associative/Multidimensional Arrays.
Basic Explanation
Many array functions in PHP follow similar patterns:
- Some functions return a new array (e.g., arraymap, arrayfilter, arraymerge) — they do not modify the original.
- Others modify the array in place (e.g., shuffle, arraysplice) — changes apply to the original.
- Some functions work with a callback (anonymous function or function name), which PHP calls for each element.
- Many functions support strict comparison modes, helping avoid subtle bugs.
PHP Code Examples
Transforming: arraymap, arraywalk, arraywalkrecursive
<?php
// array_map — creates a NEW array based on transforming values
$prices = [10, 20.5, 30];
$withVat = array_map(fn($p) => $p * 1.23, $prices);
// $withVat: [12.3, 25.215, 36.9]; $prices unchanged
// array_walk — iterates and allows modifying in place
$names = ['jan', 'ANNA', 'KaSpEr'];
array_walk($names, function (&$value) {
$value = ucfirst(strtolower($value)); // Jan, Anna, Kasper
});
// array_walk_recursive — also works for nested arrays
$data = [
'user' => ['NAME' => 'ALICJA', 'CITY' => 'WARSZAWA'],
'meta' => ['ROLE' => 'ADMIN']
];
array_walk_recursive($data, function (&$v, $k) {
$v = is_string($v) ? strtolower($v) : $v;
});
// All strings in $data are now lowercase
Filtering: arrayfilter, arrayunique
<?php
$numbers = [0, 1, 2, 3, 4, 5];
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
// Keeps original keys: [0 => 0, 2 => 2, 4 => 4]
// Use keys in callback:
$assoc = ['a' => 1, 'b' => 2, 'c' => 1];
$onlyValue1 = array_filter($assoc, fn($v, $k) => $v === 1, ARRAY_FILTER_USE_BOTH);
// array_unique — removes duplicate values (keeps first occurrence)
$vals = [10, 10, '10', 20];
$uniqueLoose = array_unique($vals); // [10, '10', 20]
$uniqueStrict = array_unique($vals, SORT_STRING); // treats numbers as strings
Reduction and Aggregation: arrayreduce, arraysum, arrayproduct
<?php
$orders = [
['id' => 1, 'total' => 99.99],
['id' => 2, 'total' => 149.50],
['id' => 3, 'total' => 10.00],
];
$total = array_reduce($orders, fn($carry, $o) => $carry + $o['total'], 0.0);
// $total: 259.49
$nums = [2, 3, 4];
echo array_sum($nums); // 9
echo array_product($nums); // 24
Columns and Restructuring: arraycolumn, arraycombine, arrayflip, arraychangekeycase
<?php
$users = [
['id' => 10, 'name' => 'Ala', 'email' => 'ala@example.com'],
['id' => 11, 'name' => 'Ola', 'email' => 'ola@example.com'],
];
$emails = array_column($users, 'email');
$byId = array_column($users, 'email', 'id');
$keys = ['pl', 'en', 'de'];
$values = ['Witaj', 'Hello', 'Hallo'];
$map = array_combine($keys, $values);
$flipped = array_flip(['a' => 1, 'b' => 2]); // [1 => 'a', 2 => 'b']
$raw = ['Name' => 'Ada', 'EMAIL' => 'ada@example.com'];
$lower = array_change_key_case($raw, CASE_LOWER);
Keys and Values: arraykeys, arrayvalues, arraykeyfirst/last, arraykeyexists
<?php
$assoc = ['a' => 10, 'b' => 20, 'c' => 10];
$keysAll = array_keys($assoc);
$keysFor10 = array_keys($assoc, 10, true);
$vals = array_values($assoc);
$firstKey = array_key_first($assoc);
$lastKey = array_key_last($assoc);
var_dump(array_key_exists('a', $assoc)); // true
Set Comparisons: arraydiff, arraydiffassoc, arrayintersect, arrayintersectkey
<?php
$a = ['a' => 1, 'b' => 2, 'c' => 3];
$b = ['a' => 1, 'b' => 99, 'd' => 4];
var_dump(array_diff($a, $b));
var_dump(array_diff_assoc($a, $b));
var_dump(array_intersect($a, $b));
var_dump(array_intersect_key($a, $b));
Combining and Replacing: arraymerge, arraymergerecursive, arrayreplace, operator +
<?php
$one = ['a' => 1, 'b' => 2];
$two = ['b' => 20, 'c' => 3];
var_dump(array_merge($one, $two));
var_dump(array_merge_recursive($one, $two));
var_dump(array_replace($one, $two));
var_dump($one + $two);
Generating and Filling: range, arrayfill, arrayfillkeys, arraypad
<?php
$nums = range(1, 5);
$letters = range('a', 'e');
$filled = array_fill(0, 3, 'X');
$keys = ['id', 'name', 'email'];
$empty = array_fill_keys($keys, null);
$base = [1, 2];
$padded = array_pad($base, 5, 0);
$leftPad = array_pad($base, -5, 0);
Randomness and Shuffling: shuffle, arrayrand
<?php
$items = ['a','b','c','d'];
shuffle($items);
$colors = ['red' => '#f00', 'green' => '#0f0', 'blue' => '#00f'];
$oneKey = array_rand($colors);
$twoKeys = array_rand($colors, 2);
Reversing: arrayreverse
<?php
$nums = [1, 2, 3];
$reversed = array_reverse($nums);
$assoc = ['a'=>1,'b'=>2,'c'=>3];
$revAssoc = array_reverse($assoc, true);
Searching: inarray, arraysearch
<?php
$vals = [0, '0', false, null, 1];
var_dump(in_array('0', $vals));
var_dump(in_array('0', $vals, true));
var_dump(in_array(0, $vals, true));
var_dump(in_array('', $vals, true));
$key = array_search(false, $vals, true);
if ($key !== false) {
// Found safely
}
Utilities: arrayislist, isarray, compact, extract (use carefully)
<?php
var_dump(array_is_list([10,20,30])); // true
var_dump(array_is_list(['a'=>1, 0=>2, 1=>3])); // false
$name = 'Ada';
$age = 30;
$user = compact('name', 'age');
$data = ['token' => 'abc', 'id' => 1];
extract($data); // creates $token, $id
Best Practices and Common Mistakes
Best Practices
- Use strict comparisons where possible: inarray(\$v, \$arr, true), arraysearch(\$v, \$arr, true).
- Distinguish between functions returning a new array vs modifying in place.
- For associative arrays, prefer arrayreplace over arraymergerecursive when you need overwrite behavior.
- Use arraycolumn to extract data from records/objects.
- After filtering with arrayfilter, use arrayvalues to reindex if continuous keys are needed.
- Validate input sizes: arraycombine requires same number of keys and values.
- Use arrayislist (PHP 8.1+) to validate list-like arrays.
Common Mistakes and Pitfalls
- Confusing loose vs strict comparisons in arraysearch (0 vs false).
- arraymerge rebuilds numeric keys, operator + preserves left keys.
- arrayflip loses data with duplicate values.
- arraymergerecursive may create nested arrays unexpectedly.
- Memory usage: arraymap/filter create new arrays — consider foreach for huge datasets.
- extract can overwrite variables and pose security risks — use sparingly.
- arrayrand returns int for 1 element, array for multiple — handle both cases.
Summary
- PHP provides a rich set of array functions: map, filter, reduce, column extraction, set comparisons, merging, generating, randomness, reversing, searching, and more.
- Choose functions that make code shorter, clearer, and less error-prone.
- Remember differences: return vs modify in place, strict comparisons, key/index handling.
- PHP 8.1+ adds arrayislist for validating list arrays.
Mini Quiz
- Which function extracts emails from a list of users? → arraycolumn
- Which function merges arrays and overwrites conflicting string keys? → arraymerge
- What does arraysearch return if not found? → false
- How to reindex after arrayfilter? → arrayvalues
- Difference between arraymerge and + for associative arrays? → arraymerge overwrites, + keeps left values
- Function to check if array has sequential 0..n keys? (PHP 8.1+) → arrayislist
- True/False: arrayflip is safe with duplicate values → False
- Sum numbers in array? → arraysum (or arrayreduce)
Practice each function with your own data. In real-world PHP projects, combining several array functions (map → filter → column) creates concise and professional code.