PHP
Apply a Callback to Multiple Arrays Simultaneously with `array_map`
Discover how to use `array_map` in PHP to process elements from several arrays in parallel with a single callback function.
<?php
$names = ['Alice', 'Bob', 'Charlie'];
$ages = [30, 24, 35];
$cities = ['New York', 'London', 'Paris'];
// Combine information from all three arrays into an array of associative arrays
$usersData = array_map(function($name, $age, $city) {
return [
'name' => $name,
'age' => $age,
'city' => $city
];
}, $names, $ages, $cities);
print_r($usersData);
/*
Output will be:
Array
(
[0] => Array
(
[name] => Alice
[age] => 30
[city] => New York
)
[1] => Array
(
[name] => Bob
[age] => 24
[city] => London
)
[2] => Array
(
[name] => Charlie
[age] => 35
[city] => Paris
)
)
*/
// Example 2: Calculate total prices
$quantities = [2, 3, 1, 4];
$unitPrices = [10.50, 5.25, 20.00, 3.75];
$totalPrices = array_map(function($qty, $price) {
return $qty * $price;
}, $quantities, $unitPrices);
print_r($totalPrices);
/*
Output will be:
Array
(
[0] => 21
[1] => 15.75
[2] => 20
[3] => 15
)
*/
?>
How it works: The `array_map` function is highly versatile and can take multiple arrays as arguments, not just one. This snippet demonstrates how a single callback function can process elements from several input arrays simultaneously. Each argument passed to the callback corresponds to an element from the respective input array at the same index. This is incredibly useful for combining, transforming, or calculating new values based on parallel data sets.