The array_map() function in PHP is used to apply a callback function to each element of an array (or multiple arrays) and return a new transformed array. It is commonly used for data transformation and formatting.
Syntax
// General syntax of array_map()
array_map(callback, array1, array2, ...);
This example squares each number in an array.
// Square each number using array_map()
<?php
$numbers = array(1, 2, 3, 4, 5);
$squared = array_map(function($num) {
return $num * $num;
}, $numbers);
print_r($squared);
?>
Each element of the original array is squared and stored in a new array. The original array remains unchanged.
// Combine names and ages using multiple arrays
<?php
$names = array("John", "Jane", "Doe");
$ages = array(22, 28, 31);
$combined = array_map(function($name, $age) {
return $name . " is " . $age . " years old.";
}, $names, $ages);
print_r($combined);
?>
// Convert all strings to uppercase
<?php
$words = array("hello", "world", "php");
$uppercased = array_map('strtoupper', $words);
print_r($uppercased);
?>
array_map() transformation flow
array_map() when immutability is desired