How to use PHP ‘array_map’ with example

The php array_map method is used to apply a specified callback function to each element of one or more arrays passed in the array_map function as the arguments.

Syntax of array_map

array_map(myfunction, array1, array2, array3, …)

Return value of array_map

Returns an array containing the result of applied callback function on one or more arrays passed as arguments.

Examples of php array_map

1. Applying a Function to Each Element of an Array

PHP
<?php

// Example callback function
function square($value) {
    return $value * $value;
}

// Original array
$numbers = [1, 2, 3, 4, 5];

// Applying array_map with the square function
$squaredNumbers = array_map('square', $numbers);

// Displaying the results
var_dump($squaredNumbers); 
// Output: array(5) { [0]=> int(1) [1]=> int(4) [2]=> int(9) [3]=> int(16) [4]=> int(25) }

2. Using Anonymous Function

PHP
<?php

// Original array
$grades = [85, 92, 78, 95, 88];

// Applying array_map with an anonymous function to add 5 to each grade
$adjustedGrades = array_map(function ($grade) {
    return $grade + 5;
}, $grades);

// Displaying the results
var_dump($adjustedGrades); 
// Output: array(5) { [0]=> int(90) [1]=> int(97) [2]=> int(83) [3]=> int(100) [4]=> int(93) }

3. Applying Function to Multiple Arrays

PHP
<?php

// Example callback function
function sum($a, $b) {
    return $a + $b;
}

// Original arrays
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];

// Applying array_map with the sum function to two arrays
$sumArray = array_map('sum', $array1, $array2);

// Displaying the results
var_dump($sumArray); 
// Output: array(3) { [0]=> int(5) [1]=> int(7) [2]=> int(9) }

4. Applying Function to Three Arrays

PHP
<?php

// Example callback function
function product($a, $b, $c) {
    return $a * $b * $c;
}

// Original arrays
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$array3 = [7, 8, 9];

// Applying array_map with the product function to three arrays
$productArray = array_map('product', $array1, $array2, $array3);

// Displaying the results
var_dump($productArray); 
// Output: array(3) { [0]=> int(28) [1]=> int(80) [2]=> int(162) }

Leave a Reply

Your email address will not be published. Required fields are marked *