← Back to Chapters

PHP array_map() Function

? PHP array_map() Function

? Quick Overview

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.

? Key Concepts

  • Applies a callback function to each array element
  • Returns a new array
  • Supports multiple input arrays
  • Does not modify the original array

? Syntax / Theory

Syntax

? View Code Example
// General syntax of array_map()
array_map(callback, array1, array2, ...);

? Example 1: Using array_map()

This example squares each number in an array.

? View Code Example
// 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);
?>

? Output Explanation

Each element of the original array is squared and stored in a new array. The original array remains unchanged.

? Example 2: Using array_map() with Multiple Arrays

? View Code Example
// 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);
?>

✨ Example 3: Text Transformation

? View Code Example
// Convert all strings to uppercase
<?php
$words = array("hello", "world", "php");
$uppercased = array_map('strtoupper', $words);
print_r($uppercased);
?>

? Interactive Visualization

array_map() transformation flow

Original Array Callback New Array

? Use Cases

  • Formatting API response data
  • Applying calculations to numeric datasets
  • Transforming strings (case, trimming, encoding)
  • Merging related array values

✅ Tips & Best Practices

  • Use anonymous functions for simple transformations
  • Prefer array_map() when immutability is desired
  • Ensure arrays have equal length when using multiple arrays

? Try It Yourself

  • Multiply each number in an array by 10
  • Format employee names with salaries
  • Convert an array of strings to lowercase
  • Reverse each string using a custom callback