PHP Array Functions
PHP ships with a large library of built-in functions that transform, filter, sort, and combine arrays without writing loops by hand.
Why use array functions?
Almost anything you might do to an array by writing a loop already has a well-tested built-in function. Reaching for these functions makes your code shorter, clearer, and usually faster, and it signals intent to other developers. This page covers the functions you will use most often, grouped by what they do.
Counting, searching, and testing
Finding what is in an array
<?php
$nums = [10, 20, 30, 40];
echo count($nums); // 4
var_dump(in_array(30, $nums)); // bool(true)
echo array_search(40, $nums); // 3 (the key)
var_dump(array_key_exists(2, $nums)); // bool(true)
?>Transforming arrays
array_map() applies a function to every element and returns a new array of the results, while array_filter() keeps only the elements that pass a test. array_reduce() collapses a whole array down to a single value. None of these change the original array.
map, filter, and reduce
<?php
$numbers = [1, 2, 3, 4, 5];
$doubled = array_map(fn($n) => $n * 2, $numbers);
// [2, 4, 6, 8, 10]
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);
// [1 => 2, 3 => 4]
$total = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
// 15
print_r($doubled);
?>Sorting arrays
PHP offers a family of sort functions that differ in whether they preserve keys and whether they sort by value or by key. All of them sort the array in place and return true on success rather than a new array.
Sorting values and keys
<?php
$scores = [3, 1, 2];
sort($scores); // [1, 2, 3], keys reindexed
$ages = ["Ravi" => 30, "Mei" => 25];
asort($ages); // sort by value, keep keys
ksort($ages); // sort by key alphabetically
print_r($ages);
?>Common array functions at a glance
- array_merge() renumbers integer keys but overwrites duplicate string keys with the later value.
- explode() and implode() convert between strings and arrays, which is handy for CSV-style data.
- array_unique() removes duplicate values, and array_reverse() flips the order.
- Most transforming functions return a new array, while most sorting functions modify in place.