PHP Array Iteration
Beyond basic foreach loops, PHP provides powerful functional-style array functions. These let you transform, filter, and reduce arrays with clean, expressive code that's easy to read and maintain.
Functional Array Functions Overview
| Function | Purpose | Returns |
|---|---|---|
array_map() |
Transform each element | New array (same length) |
array_filter() |
Keep matching elements | New array (subset) |
array_reduce() |
Combine to single value | Single value |
array_walk() |
Apply function (in place) | true/false |
array_map() - Transform Elements
Apply a function to each element and return a new array:
<?php
$numbers = [1, 2, 3, 4, 5];
// Square each number
$squared = array_map(fn($n) => $n * $n, $numbers);
// [1, 4, 9, 16, 25]
// Format prices
$prices = [10, 25.5, 99.99];
$formatted = array_map(fn($p) => "$" . number_format($p, 2), $prices);
// ["$10.00", "$25.50", "$99.99"]
// Extract property from objects
$users = [
["name" => "Alice", "age" => 25],
["name" => "Bob", "age" => 30]
];
$names = array_map(fn($u) => $u["name"], $users);
// ["Alice", "Bob"]
?>
Click Run to execute your code
array_map() puts the callback first, then
the array(s).
This is opposite of array_filter() and array_reduce()!
array_filter() - Keep Matching Elements
Filter elements based on a condition:
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Keep even numbers
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);
// [2, 4, 6, 8, 10]
// Keep positive values
$mixed = [-5, 0, 3, -2, 8, -1];
$positive = array_filter($mixed, fn($n) => $n > 0);
// [3, 8]
// Without callback - removes "falsy" values
$data = [0, 1, "", "hello", null, false, []];
$truthy = array_filter($data);
// [1, "hello"]
// Filter by key
$arr = ["a" => 1, "b" => 2, "c" => 3];
$filtered = array_filter($arr, fn($k) => $k !== "b", ARRAY_FILTER_USE_KEY);
// ["a" => 1, "c" => 3]
?>
array_filter() preserves keys! Use
array_values() if you need reindexing.
array_reduce() - Combine to Single Value
Reduce an array to a single value by applying a function cumulatively:
<?php
$numbers = [1, 2, 3, 4, 5];
// Sum all values
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
// 15
// Product of all values
$product = array_reduce($numbers, fn($carry, $n) => $carry * $n, 1);
// 120
// Find maximum
$max = array_reduce($numbers, fn($carry, $n) => max($carry, $n), PHP_INT_MIN);
// 5
// Build string
$words = ["Hello", "World"];
$sentence = array_reduce($words, fn($c, $w) => $c ? "$c $w" : $w, "");
// "Hello World"
// Build associative array
$items = [["id" => 1, "val" => "a"], ["id" => 2, "val" => "b"]];
$indexed = array_reduce($items, function($carry, $item) {
$carry[$item["id"]] = $item["val"];
return $carry;
}, []);
// [1 => "a", 2 => "b"]
?>
array_walk() - Modify In Place
Apply a function to each element, modifying the original array:
<?php
$prices = [100, 200, 300];
// Apply 10% discount (modify in place)
array_walk($prices, function(&$price) {
$price *= 0.9;
});
// $prices is now [90, 180, 270]
// With key access
$inventory = ["apples" => 50, "bananas" => 30];
array_walk($inventory, function(&$qty, $item) {
echo "Checking $item: $qty units\n";
$qty += 10; // Add 10 to each
});
// Pass extra data
$rates = [100, 200, 300];
$taxRate = 0.08;
array_walk($rates, function(&$val, $key, $tax) {
$val *= (1 + $tax);
}, $taxRate);
?>
Chaining Operations
Combine functions for complex transformations:
<?php
$users = [
["name" => "Alice", "age" => 25, "active" => true],
["name" => "Bob", "age" => 17, "active" => true],
["name" => "Carol", "age" => 30, "active" => false],
["name" => "David", "age" => 22, "active" => true]
];
// Get names of active adult users
$result = array_map(
fn($u) => $u["name"],
array_filter($users, fn($u) => $u["active"] && $u["age"] >= 18)
);
// ["Alice", "David"]
// Calculate average age of active users
$activeUsers = array_filter($users, fn($u) => $u["active"]);
$totalAge = array_reduce($activeUsers, fn($sum, $u) => $sum + $u["age"], 0);
$avgAge = $totalAge / count($activeUsers);
?>
Click Run to execute your code
Useful Related Functions
<?php
// array_column - Extract column from 2D array
$users = [
["id" => 1, "name" => "Alice"],
["id" => 2, "name" => "Bob"]
];
$names = array_column($users, "name"); // ["Alice", "Bob"]
$byId = array_column($users, "name", "id"); // [1 => "Alice", 2 => "Bob"]
// array_sum / array_product
$numbers = [1, 2, 3, 4, 5];
echo array_sum($numbers); // 15
echo array_product($numbers); // 120
// array_count_values
$votes = ["yes", "no", "yes", "yes", "no"];
$counts = array_count_values($votes);
// ["yes" => 3, "no" => 2]
// array_diff / array_intersect
$a = [1, 2, 3, 4, 5];
$b = [3, 4, 5, 6, 7];
array_diff($a, $b); // [1, 2]
array_intersect($a, $b); // [3, 4, 5]
?>
When to Use Each
| Task | Use |
|---|---|
| Transform each element | array_map() |
| Remove some elements | array_filter() |
| Calculate total/aggregate | array_reduce() |
| Modify original array | array_walk() |
| Extract single column | array_column() |
| Sum numbers | array_sum() |
Exercise: Data Pipeline
Task: Process sales data using functional array functions.
Requirements:
- Filter out cancelled orders
- Calculate total for each order (price ร quantity)
- Get total revenue
- Find the highest value order
Show Solution
<?php
$orders = [
["id" => 1, "product" => "Widget", "price" => 25, "qty" => 4, "status" => "completed"],
["id" => 2, "product" => "Gadget", "price" => 50, "qty" => 2, "status" => "cancelled"],
["id" => 3, "product" => "Tool", "price" => 35, "qty" => 3, "status" => "completed"],
["id" => 4, "product" => "Device", "price" => 100, "qty" => 1, "status" => "completed"],
["id" => 5, "product" => "Part", "price" => 15, "qty" => 10, "status" => "cancelled"]
];
// 1. Filter out cancelled orders
$activeOrders = array_filter($orders, fn($o) => $o["status"] !== "cancelled");
// 2. Calculate total for each order
$ordersWithTotal = array_map(fn($o) => [
...$o,
"total" => $o["price"] * $o["qty"]
], $activeOrders);
// 3. Get total revenue
$totalRevenue = array_reduce($ordersWithTotal, fn($sum, $o) => $sum + $o["total"], 0);
// 4. Find highest value order
$highestOrder = array_reduce($ordersWithTotal, function($max, $o) {
return ($o["total"] > ($max["total"] ?? 0)) ? $o : $max;
}, []);
echo "Active Orders:\n";
foreach ($ordersWithTotal as $order) {
echo " Order #{$order['id']}: {$order['product']} - ${$order['total']}\n";
}
echo "\nTotal Revenue: $$totalRevenue\n";
echo "Highest Order: #{$highestOrder['id']} ({$highestOrder['product']}) - ${$highestOrder['total']}\n";
?>
Summary
- array_map(): Transform each element โ new array
- array_filter(): Keep matching elements โ subset array
- array_reduce(): Combine to single value
- array_walk(): Modify array in place
- Chain functions: Combine for complex pipelines
- Use arrow functions:
fn($x) => $x * 2for concise code - array_filter preserves keys: Use array_values() to reindex
What's Next?
Finally, let's learn about Array Sorting - PHP's many sorting functions and how to create custom sort comparisons!
Enjoying these tutorials?