PHP
Transform Array Values Using a Callback Function in PHP
Learn how to use `array_map()` to apply a custom callback function to every element of one or more PHP arrays, creating a new transformed array.
<?php
$numbers = [1, 2, 3, 4, 5];
// 1. Double each number
$doubledNumbers = array_map(function($n) {
return $n * 2;
}, $numbers);
echo "Original numbers: " . implode(", ", $numbers) . "
";
echo "Doubled numbers: " . implode(", ", $doubledNumbers) . "
";
// 2. Format names to uppercase
$names = ["alice", "bob", "charlie"];
$formattedNames = array_map('ucfirst', $names); // Using a built-in function
echo "Original names: " . implode(", ", $names) . "
";
echo "Formatted names: " . implode(", ", $formattedNames) . "
";
// 3. Combine two arrays into an array of strings
$firstNames = ["John", "Jane"];
$lastNames = ["Doe", "Smith"];
$fullNames = array_map(function($firstName, $lastName) {
return "$firstName $lastName";
}, $firstNames, $lastNames);
echo "Full names: " . implode(", ", $fullNames) . "
";
?>
How it works: The `array_map()` function iterates over each element of an array (or multiple arrays) and applies a specified callback function to it. It then returns a new array containing the values returned by the callback function for each element. This is ideal for transforming data without altering the original array, such as converting data types, applying mathematical operations, or formatting strings.