How Does array_map() Work Behind the Scenes? - PHP

271 views Asked by At

I implemented array_map() as follows:

$example = array(' [email protected]', '[email protected] ');

$result = array_map(function($email) {
    return trim($email);
}, $example);

// $result now has each item trimmed
// IE: '[email protected]', '[email protected]' ..

This got me to wondering...

Q How exactly is array_map() working behind the scenes?

1

There are 1 answers

1
Lodo On

You can also explain this way by using a closure to a function :

function map($func, $items)
{
    $result = [];

    foreach ($items as $item) {
        $result[] = $func($item);
    }

    return $result;
}

$result = map(function($email) {
    return trim($email);
}, $example);