Written by James McDonald

May 18, 2022

array_map can take multiple arrays.

I like how it starts mapping through them starting at the first element of each array all together and then keeps mapping until it completes the largest array.

Each argument to the callback function is the current element of the arrays you have passed into array_map

Unlike using array_map on one array where it passes the entire key=>value pair of each element into the callback. When using multiple arrays it only passes the value into array map not the key. So the associative array just uses the values and loses the key.

<?php

$arr1 = ['a', 'b', 'c'];
$arr2 = ['aa', 'bb', 'cc'];
$arr3 = [1, 2, 3, 4, 5, 6];
$arr4 = ['a' => 1, 'b' => 2, 'c' => 3];
$arr5 = ['head' => 'H'];

$mapped = array_map(function ($one, $two, $three, $four, $five) {
    return compact('one', 'two', 'three', 'four', 'five');
}, $arr1, $arr2, $arr3, $arr4, $arr5);

echo print_r($mapped, true);

// output
// you lose the array keys
Array
(
    [0] => Array
        (
            [one] => a
            [two] => aa
            [three] => 1
            [four] => 1
            [five] => H
        )

    [1] => Array
        (
            [one] => b
            [two] => bb
            [three] => 2
            [four] => 2
            [five] => 
        )

    [2] => Array
        (
            [one] => c
            [two] => cc
            [three] => 3
            [four] => 3
            [five] => 
        )

    [3] => Array
        (
            [one] => 
            [two] => 
            [three] => 4
            [four] => 
            [five] => 
        )

    [4] => Array
        (
            [one] => 
            [two] => 
            [three] => 5
            [four] => 
            [five] => 
        )

    [5] => Array
        (
            [one] => 
            [two] => 
            [three] => 6
            [four] => 
            [five] => 
        )

)

Example of passing a single array into array_map (keys are available)

$mapped2 = array_map(function ($el) {
    return $el;
}, ['a' => 1, 'b' => 2, 'c' => 3]);

echo print_r($mapped2, true);

// output
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)

0 Comments

Submit a Comment

Your email address will not be published.

You May Also Like…

MacOS USB Creator

Just toasted my Windows 10 Pro install with a Windows 11 upgrade. Think it will be unrecoverable (because of Bitlocker...