Array Functions
PHP ships with well over 80 built-in functions for working with arrays, covering transformation, filtering, searching, sorting, and aggregation. Learning the core set — array_map, array_filter, array_reduce, array_search, in_array, and the sort family — replaces the vast majority of manual for/foreach loops with concise, expressive, and typically faster code, since these functions are implemented in C at the engine level rather than interpreted PHP. Understanding which functions preserve keys, which reindex, and which mutate in place versus return a new array is essential to using them correctly.
Cricket analogy: A scorer who knows shortcuts like strike-rate and net-run-rate formulas doesn't manually tally every ball from scratch; PHP's 80+ built-in array functions like array_map and array_filter are the same pre-built formulas, running faster than hand-rolled foreach loops because they execute in compiled C, not interpreted PHP.
Transforming: array_map and array_filter
array_map() applies a callback to every element of one or more arrays and returns a new array of the results, preserving keys when a single array is passed. array_filter() returns a new array containing only the elements for which a callback returns true (or, with no callback, the elements that are truthy), and crucially it preserves the original keys — a frequent source of confusion when the result is later expected to be a clean 0-indexed list, which requires an explicit array_values() call.
Cricket analogy: array_map running a callback over the batting lineup and returning a new array of adjusted scores while keeping each player's original batting position is like reviewing a scorecard where every player's slot stays fixed even after recalculating strike rates; array_filter keeping the original numbering when trimming out ducks is the same, needing array_values to renumber cleanly for a fresh scorecard.
$prices = [10, 25, 3, 47, 8];
$withTax = array_map(fn(float $p): float => round($p * 1.2, 2), $prices);
$expensive = array_values(
array_filter($prices, fn(float $p): bool => $p > 20)
);
print_r($withTax); // [12, 30, 3.6, 56.4, 9.6]
print_r($expensive); // [25, 47]Aggregating: array_reduce
array_reduce() collapses an array into a single value by repeatedly applying a callback that receives an accumulator and the current item, starting from an optional initial value. It is the general-purpose tool behind sums, products, groupings, and flattenings when a specialized function like array_sum() doesn't already exist for the job.
Cricket analogy: array_reduce collapsing an array of over-by-over scores into a single match total, using an accumulator that starts at zero and adds each over, is the general-purpose tool behind computing a team's final total when there's no dedicated array_sum-style function for run-rate-weighted totals.
$orders = [
['item' => 'Book', 'qty' => 2, 'price' => 15],
['item' => 'Pen', 'qty' => 5, 'price' => 2],
];
$total = array_reduce(
$orders,
fn(float $carry, array $order): float => $carry + $order['qty'] * $order['price'],
0.0
);
echo $total; // 40.0Searching and Sorting
in_array() checks for a value's presence (use the strict third argument to avoid loose == comparisons like '0' == false), while array_search() returns the matching key or false. The sort family splits into functions that sort by value and reindex (sort, rsort), by value while preserving keys (asort, arsort), by key (ksort, krsort), and custom comparator variants (usort, uasort, uksort) for complex ordering logic like sorting objects by a property. All of these sort functions mutate the array in place and return a boolean, not a new sorted array.
Cricket analogy: in_array() checking whether 'Kohli' is present in a squad list using the strict flag (to avoid '0' loosely matching false) is like a scorer double-checking a name against the exact roster rather than a fuzzy guess; usort sorting players by strike rate with a custom comparator mutates the lineup array in place rather than returning a fresh one.
A useful mental model: functions starting with 'u' (usort, uasort, uksort) take a user-defined comparison callback, functions with an 'a' preserve associative keys (asort, arsort), and functions with a 'k' sort by key rather than value (ksort, krsort). Combining these letters tells you the behavior without memorizing each function individually.
in_array($needle, $haystack) defaults to loose comparison, so in_array('0', ['abc', 'def']) can return unexpected results in older PHP versions due to numeric-string coercion quirks. Always pass true as the third argument (in_array($needle, $haystack, true)) for strict comparison unless loose matching is genuinely intended.
array_map()transforms every element and preserves keys for a single-array call;array_filter()keeps matching elements and always preserves original keys.array_reduce()folds an array down to a single accumulated value using a callback and optional initial value.in_array()andarray_search()locate values; always passtruefor strict comparison to avoid loose-comparison bugs.- Sort functions like
sort,asort,ksort, and theiru*comparator variants mutate the array in place and return a boolean. array_filter()results often needarray_values()afterward to get a clean, reindexed list.- Built-in array functions are implemented natively and are generally faster and more readable than manual loops for the same task.
Practice what you learned
1. What does array_filter() do to the array keys of the elements it keeps?
2. Which function collapses an array into a single accumulated value using a callback?
3. Why should you pass true as the third argument to in_array()?
4. What do sort functions like sort(), asort(), and usort() return?
5. Which sort function lets you sort an array of objects by a custom property using your own comparison logic?
Was this page helpful?
You May Also Like
Indexed and Associative Arrays
Understand PHP's single array type used for both ordered lists and key-value maps, including creation, iteration, and common manipulation patterns.
Functions in PHP
Learn how PHP functions are declared, typed, and invoked, including default parameters, variadics, references, and closures for reusable logic.
String Functions and Formatting
Master PHP's core string manipulation and formatting functions, from searching and slicing to sprintf-style output and multibyte-safe operations.
Working with JSON in PHP
Learn how to encode PHP data to JSON and decode JSON back into PHP values using json_encode and json_decode, plus common pitfalls and error handling.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics