PHP
Transform All Elements of an Array Using a Callback
Discover how to use PHP's `array_map()` function to apply a custom transformation callback to every element of an array, generating a new array with modified values.
<?php
$numbers = [1, 2, 3, 4, 5];
// Example 1: Double each number
$doubledNumbers = array_map(function($n) {
return $n * 2;
}, $numbers);
echo "Doubled Numbers:
";
print_r($doubledNumbers);
$products = [
['name' => 'Laptop', 'price' => 1200],
['name' => 'Mouse', 'price' => 25],
['name' => 'Keyboard', 'price' => 75]
];
// Example 2: Add a tax to each product price
$productsWithTax = array_map(function($product) {
$product['price'] = $product['price'] * 1.08; // Add 8% tax
return $product;
}, $products);
echo "
Products with Tax:
";
print_r($productsWithTax);
/*
Expected Output:
Doubled Numbers:
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)
Products with Tax:
Array
(
[0] => Array
(
[name] => Laptop
[price] => 1296
)
[1] => Array
(
[name] => Mouse
[price] => 27
)
[2] => Array
(
[name] => Keyboard
[price] => 81
)
)
*/
?>
How it works: The `array_map()` function is invaluable for applying a user-defined callback function to each element of one or more arrays, returning a new array containing the results. It's perfect for transformations like modifying values, reformatting data, or adding new properties to associative array elements without iterating manually.