Transforming with 'array_map'
Part of the Logic & Flow section of Coddy's PHP journey — lesson 39 of 68.
The array_map() function is a powerful tool that transforms every element in an array by applying a callback function to each one. Unlike functions that modify the original array, array_map() creates and returns a completely new array with the transformed values.
The basic syntax requires two parameters: first, the callback function you want to apply, and second, the array you want to transform. PHP has many built-in functions that work perfectly as callbacks with array_map().
<?php
$names = ["alice", "bob", "charlie"];
$uppercaseNames = array_map("strtoupper", $names);
// Result: ["ALICE", "BOB", "CHARLIE"]
?>In this example, strtoupper is applied to each element in the $names array. The original array remains unchanged, while $uppercaseNames contains the transformed results. This makes array_map() ideal when you need to process data without losing the original values.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou will receive two inputs: a comma-separated list of product prices and a discount percentage. The first input contains prices as a string in the format 19.99,25.50,12.75,8.00, and the second input is the discount percentage as a number (example: 15).
Read both inputs, convert the comma-separated prices into an array of numbers, apply the discount percentage to each price using array_map() with the built-in floatval function for conversion and a calculation for the discount, and print each discounted price on a separate line, rounded to 2 decimal places.
To calculate the discounted price: multiply the original price by (100 - discount) / 100.
Input format:
- First line: Comma-separated product prices (example:
19.99,25.50,12.75,8.00) - Second line: Discount percentage as a number (example:
15)
Expected output: Each discounted price printed on a separate line, rounded to 2 decimal places (example: 16.99, 21.68, 10.84, 6.80)
Cheat sheet
The array_map() function transforms every element in an array by applying a callback function to each one. It creates and returns a new array with the transformed values, leaving the original array unchanged.
Basic syntax with built-in function:
<?php
$names = ["alice", "bob", "charlie"];
$uppercaseNames = array_map("strtoupper", $names);
// Result: ["ALICE", "BOB", "CHARLIE"]
?>The function takes two parameters: the callback function and the array to transform. You can use built-in PHP functions or anonymous functions as callbacks.
Try it yourself
<?php
// Read input
$prices_input = trim(fgets(STDIN));
$discount = floatval(fgets(STDIN));
// Convert comma-separated prices to array
$prices = explode(',', $prices_input);
// TODO: Write your code below
// Use array_map() to apply the discount to each price
// Output each discounted price on a separate line
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting6Higher-Order Array Functions
Transforming with 'array_map''array_map' with Custom FuncFiltering with 'array_filter''array_filter' with Custom FunReducing with 'array_reduce'Walking with 'array_walk'Recap: Data Processing