PHP
Transforming PHP Array Values with a Custom Callback
Learn to apply a custom function to each element of a PHP array, creating a new array with transformed values using the `array_map` function.
<?php
$numbers = [1, 2, 3, 4, 5];
// Example 1: Double each number
$doubledNumbers = array_map(function($number) {
return $number * 2;
}, $numbers);
// $doubledNumbers will be [2, 4, 6, 8, 10]
$products = [
['name' => 'Laptop', 'price' => 1200],
['name' => 'Mouse', 'price' => 25],
['name' => 'Keyboard', 'price' => 75]
];
// Example 2: Add tax to product prices
$productsWithTax = array_map(function($product) {
$product['price'] = $product['price'] * 1.05; // 5% tax
return $product;
}, $products);
/*
$productsWithTax will be:
[
['name' => 'Laptop', 'price' => 1260.0],
['name' => 'Mouse', 'price' => 26.25],
['name' => 'Keyboard', 'price' => 78.75]
]
*/
?>
How it works: The `array_map()` function applies a user-defined callback function to each element of one or more arrays. It iterates through the array(s) and creates a new array containing the values returned by the callback. This is an efficient way to transform the data structure or values of an array without directly modifying the original.