PHP
Apply a Function to Each PHP Array Element
Transform each element of a PHP array by applying a user-defined callback function using array_map(), returning a new array with the modified values.
<?php
$numbers = [1, 2, 3, 4, 5];
// Double each number
$doubledNumbers = array_map(function($n) {
return $n * 2;
}, $numbers);
print_r($doubledNumbers);
/* Output:
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)
*/
// Convert strings to uppercase using a built-in function
$names = ['alice', 'bob', 'charlie'];
$uppercaseNames = array_map('strtoupper', $names);
print_r($uppercaseNames);
/* Output:
Array
(
[0] => ALICE
[1] => BOB
[2] => CHARLIE
)
*/
// With multiple arrays (elements are passed in order to the callback)
$firstNames = ['John', 'Jane'];
$lastNames = ['Doe', 'Smith'];
$fullNames = array_map(function($first, $last) {
return "$first $last";
}, $firstNames, $lastNames);
print_r($fullNames);
/* Output:
Array
(
[0] => John Doe
[1] => Jane Smith
)
*/
How it works: The `array_map()` function applies a specified callback function to each element of one or more arrays. It returns a new array containing the results of applying the callback. This is highly useful for transforming data, such as changing data types, formatting strings, or performing calculations on each item in an array without modifying the original array. When multiple arrays are provided, the callback receives elements from each array in corresponding order.