PHP
Transform Each Element in an Array with a Callback Function
Learn to apply a transformation function to every element of a PHP array using `array_map`, useful for formatting or modifying data consistently.
<?php
$products = ['apple', 'banana', 'orange'];
// Capitalize each product name
$capitalizedProducts = array_map('ucfirst', $products);
print_r($capitalizedProducts);
// Output:
// Array
// (
// [0] => Apple
// [1] => Banana
// [2] => Orange
// )
$numbers = [1, 2, 3, 4];
// 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
// )
$users = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25]
];
// Extract only names
$userNames = array_map(function($user) {
return $user['name'];
}, $users);
print_r($userNames);
// Output:
// Array
// (
// [0] => Alice
// [1] => Bob
// )
?>
How it works: `array_map()` 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 to each original element. This function is ideal for transforming data in a consistent way, such as formatting strings, performing calculations, or modifying object properties across an entire collection.