PHP
Transforming Array Values Using `array_map`
Learn to apply a callback function to every element in an array with PHP's `array_map`, efficiently transforming data for various presentation or processing needs.
<?php
$users = [
['first_name' => 'John', 'last_name' => 'Doe', 'age' => 30],
['first_name' => 'Jane', 'last_name' => 'Smith', 'age' => 24],
['first_name' => 'Peter', 'last_name' => 'Jones', 'age' => 45],
];
// Create an array of full names from user data
$fullNames = array_map(function($user) {
return $user['first_name'] . ' ' . $user['last_name'];
}, $users);
// Calculate ages in 'dog years' (approx * 7) for each user
$dogAges = array_map(function($user) {
return $user['age'] * 7;
}, $users);
echo "Full Names:
";
print_r($fullNames);
echo "
Dog Ages:
";
print_r($dogAges);
?>
How it works: The `array_map()` function applies a specified callback function to each element of one or more arrays, returning a new array containing the results. This is invaluable for transforming data, performing calculations, reformatting values, or extracting subsets of information across an entire array without needing explicit loops, promoting cleaner and more functional code.