Why Array Functions Matter
PHP arrays are ordered maps — the most versatile data structure in PHP. Mastering built-in array functions lets you write clean, readable, interview-worthy code without messy loops.
array_map() — Transform Every Element
<?php
$numbers = [1, 2, 3, 4, 5];
// Double every number
$doubled = array_map(fn($n) => $n * 2, $numbers);
// [2, 4, 6, 8, 10]
// Map with index using array_keys
$indexed = array_map(null, $numbers, array_keys($numbers));
// Real use: format prices
$prices = [999, 1499, 2999];
$formatted = array_map(fn($p) => '₹' . number_format($p), $prices);
// ['₹999', '₹1,499', '₹2,999']
// Multiple arrays
$a = [1, 2, 3];
$b = [10, 20, 30];
$sums = array_map(fn($x, $y) => $x + $y, $a, $b);
// [11, 22, 33]
array_filter() — Keep Matching Elements
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8];
// Keep only even numbers (keys preserved!)
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);
// [1=>2, 3=>4, 5=>6, 7=>8] ← original indices kept
// Re-index with array_values()
$evens = array_values(array_filter($numbers, fn($n) => $n % 2 === 0));
// [0=>2, 1=>4, 2=>6, 3=>8]
// Filter active users
$users = [
['name' => 'Rahul', 'active' => true],
['name' => 'Priya', 'active' => false],
['name' => 'Amit', 'active' => true],
];
$active = array_values(array_filter($users, fn($u) => $u['active']));
// [Rahul, Amit]
// Without callback — removes falsy values
$cleaned = array_filter([0, 1, '', 'hello', null, false, 42]);
// [1, 'hello', 42]
array_reduce() — Collapse to Single Value
<?php
$numbers = [1, 2, 3, 4, 5];
// Sum (accumulator starts at 0)
$sum = array_reduce($numbers, fn($carry, $item) => $carry + $item, 0);
// 15
// Product
$product = array_reduce($numbers, fn($carry, $item) => $carry * $item, 1);
// 120
// Real use: calculate cart total
$cart = [
['name' => 'PHP Book', 'price' => 499, 'qty' => 2],
['name' => 'JS Course', 'price' => 999, 'qty' => 1],
];
$total = array_reduce($cart, fn($carry, $item) => $carry + ($item['price'] * $item['qty']), 0);
// 1997
// Build lookup map from array of objects
$users = [['id'=>1,'name'=>'Rahul'],['id'=>2,'name'=>'Priya']];
$map = array_reduce($users, function($carry, $user) {
$carry[$user['id']] = $user['name'];
return $carry;
}, []);
// [1 => 'Rahul', 2 => 'Priya']
Sorting with usort()
<?php
$products = [
['name' => 'Laptop', 'price' => 55000],
['name' => 'Phone', 'price' => 15000],
['name' => 'Tablet', 'price' => 25000],
];
// Sort by price ascending
usort($products, fn($a, $b) => $a['price'] - $b['price']);
// Phone -> Tablet -> Laptop
// Sort by price descending
usort($products, fn($a, $b) => $b['price'] - $a['price']);
// Sort strings case-insensitively
$names = ['Zebra', 'apple', 'Mango', 'banana'];
usort($names, fn($a, $b) => strcasecmp($a, $b));
// apple, banana, Mango, Zebra
Essential Utility Functions
<?php
$arr = [3, 1, 4, 1, 5, 9, 2, 6];
$unique = array_unique($arr); // remove duplicates
$flipped = array_flip(['a'=>1,'b'=>2]); // [1=>'a', 2=>'b']
$merged = array_merge([1,2], [3,4]); // [1,2,3,4]
$slice = array_slice($arr, 2, 3); // [4,1,5]
$chunks = array_chunk([1,2,3,4,5], 2); // [[1,2],[3,4],[5]]
$key = array_search(5, $arr); // 4 (index)
$has = in_array(5, $arr); // true
// array_column — extract a column from 2D array
$users = [['id'=>1,'name'=>'Rahul'],['id'=>2,'name'=>'Priya']];
$names = array_column($users, 'name'); // ['Rahul','Priya']
$byId = array_column($users, 'name', 'id'); // [1=>'Rahul', 2=>'Priya']
Real Pipeline Example
<?php
$orders = [
['id'=>1,'amount'=>500,'status'=>'paid'],
['id'=>2,'amount'=>1200,'status'=>'pending'],
['id'=>3,'amount'=>800,'status'=>'paid'],
['id'=>4,'amount'=>300,'status'=>'cancelled'],
];
// Total of paid orders only — filter then reduce
$paidTotal = array_reduce(
array_filter($orders, fn($o) => $o['status'] === 'paid'),
fn($carry, $o) => $carry + $o['amount'],
0
);
// 1300 (500 + 800)
// Get names of paid orders — filter then map then column
$paidIds = array_column(
array_values(array_filter($orders, fn($o) => $o['status'] === 'paid')),
'id'
);
// [1, 3]
Q: Difference between array_map and array_walk?
array_map returns a new array and does not modify the original. array_walk modifies the original in place using a reference and receives the key as a second argument. Use array_map for transformations, array_walk for side effects on existing data.
Q: Why does array_filter preserve keys?
PHP preserves original keys because the array may be associative. With numeric arrays after filtering, wrap with array_values() to re-index from 0, otherwise index 0 may no longer exist and cause off-by-one bugs.
Comments (0)
No comments yet. Be the first!
Leave a Comment