The array_map() function in PHP is a powerful tool for modifying array elements. It applies a callback function to each element of an array and returns a new array containing the modified values.
Example 1: Multiplying Company Revenue by a Factor
$companies = [ "Apple" => 274.51, "Microsoft" => 168.11, "Amazon" => 469.82, "Google" => 257.63, ]; // Callback function to multiply revenue by a factor of 1.2 $multiplyRevenue = function($revenue) { return $revenue * 1.2; }; $updatedCompanies = array_map($multiplyRevenue, $companies); print_r($updatedCompanies);
This example creates an array of companies with their respective revenue values. The multiplyRevenue() callback function takes a revenue value as input and multiplies it by 1.2. The array_map() function applies this callback function to each element of the $companies array, resulting in a new array $updatedCompanies with the modified revenue values.
Example 2: Calculate Discounts on Product Prices
$products = [ ["product_id" => 1, "price" => 100], ["product_id" => 2, "price" => 150], ["product_id" => 3, "price" => 200], ]; $discountedPrices = array_map(function($product) { $discount = 0.1; $discountedPrice = $product["price"] - ($product["price"] * $discount); return ["product_id" => $product["product_id"], "discounted_price" => $discountedPrice]; }, $products); print_r($discountedPrices);
This code creates an array products containing product information. It defines a callback function that calculates a 10% discount on each product's price and returns an associative array with the product ID and discounted price. The resulting array discountedPrices contains the discounted prices of the original products.
Example 3: Increase Order Quantities by 2
$orders = array("Laptop" => 5, "Phone" => 3, "Tablet" => 2); function increaseQuantity($quantity) { return $quantity + 2; } $increasedQuantities = array_map("increaseQuantity", $orders); print_r($increasedQuantities);
The increaseQuantity function increases each order quantity by 2. The array_map() function applies this function to each element of the $orders array, resulting in a new array with increased quantities.