PHP
Transforming Array Values with `array_map` in PHP
Discover how to apply a user-defined callback function to every element of one or more arrays in PHP using `array_map`, effectively transforming their values.
<?php
$numbers = [1, 2, 3, 4, 5];
$words = ['hello', 'world', 'php'];
// Double each number in the array
$doubledNumbers = array_map(function($n) {
return $n * 2;
}, $numbers);
echo "Doubled numbers: " . implode(', ', $doubledNumbers) . "
";
// Expected: 2, 4, 6, 8, 10
// Convert each word to uppercase
$uppercaseWords = array_map('strtoupper', $words);
echo "Uppercase words: " . implode(', ', $uppercaseWords) . "
";
// Expected: HELLO, WORLD, PHP
// Process multiple arrays simultaneously
$firstNames = ['John', 'Jane'];
$lastNames = ['Doe', 'Smith'];
$fullNames = array_map(function($firstName, $lastName) {
return $firstName . ' ' . $lastName;
}, $firstNames, $lastNames);
echo "Full names: " . implode(', ', $fullNames) . "
";
// Expected: John Doe, Jane Smith
// Applying a method from an object
class StringUtil {
public static function addExclamation($str) {
return $str . '!';
}
}
$exclamatedWords = array_map(['StringUtil', 'addExclamation'], $words);
echo "Exclamated words: " . implode(', ', $exclamatedWords) . "
";
// Expected: hello!, world!, php!
?>
How it works: The `array_map()` function applies a callback function to each element of the given arrays. It returns a new array containing all elements after the callback function has been applied. This is incredibly useful for transforming data, such as modifying strings, performing calculations on numbers, or combining elements from multiple arrays into a new structure.