Php map array to variables

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

array_mapAplica la retrollamada a los elementos de los arrays dados

Descripción

array_map ( callable $callback , array $array1 , array $... = ? ) : array

Parámetros

callback

Función de retrollamada a ejecutar para cada elemento de cada array.

array1

Un array a recorrer con la función callback.

...

Lista variable de argumentos de tipo array a recorrer con la función callback.

Valores devueltos

Devuelve un array que contiene todos los elementos de array1 después de aplicar la función callback a cada uno de ellos.

Ejemplos

Ejemplo #1 Ejemplo de array_map()

<?php
function cube($n)
{
    return(
$n $n $n);
}
$a = array(12345);
$b array_map("cube"$a);
print_r($b);
?>

Este ejemplo hace que $b contenga:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

Ejemplo #2 array_map() usando una función lambda (desde PHP 5.3.0)

<?php
$func 
= function($valor) {
    return 
$valor 2;
};
print_r(array_map($funcrange(15)));
?>

Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)

Ejemplo #3 array_map() - usando más arrays

<?php
function mostrar_en_español($n$m)
{
    return(
"El número $n se llama $m en español");
}

function

correspondencia_en_español($n$m)
{
    return(array(
$n => $m));
}
$a = array(12345);
$b = array("uno""dos""tres""cuatro""cinco");$c array_map("mostrar_en_español"$a$b);
print_r($c);$d array_map("correspondencia_en_español"$a $b);
print_r($d);
?>

El resultado del ejemplo sería:

// salida de $c
Array
(
    [0] => El número 1 se llama uno en español
    [1] => El número 2 se llama dos en español
    [2] => El número 3 se llama tres en español
    [3] => El número 4 se llama cuatro en español
    [4] => El número 5 se llama cinco en español
)

// salida of $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

    [1] => Array
        (
            [2] => dos
        )

    [2] => Array
        (
            [3] => tres
        )

    [3] => Array
        (
            [4] => cuatro
        )

    [4] => Array
        (
            [5] => cinco
        )

)

Usualmente, cuando se usan dos o más arrays, estos deberían ser de la misma longitud, ya que la retrollamada se aplica en paralelo a los elementos correspondientes. Si los arrays son de longitudes diferentes, los más cortos se extenderán con elementos vacíos para que coincidan con la logintud del más largo.

Un uso interesante de esta función es la construcción de un array de arrays, lo que se puede llevar a cabo usando null como el nombre de la retrollamada.

Ejemplo #4 Crear un array de arrays

<?php
$a 
= array(12345);
$b = array("one""two""three""four""five");
$c = array("uno""dos""tres""cuatro""cinco");$d array_map(null$a$b$c);
print_r($d);
?>

El resultado del ejemplo sería:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
            [2] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
            [2] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => four
            [2] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => five
            [2] => cinco
        )

)

El array devuelto conservará las claves del argumento array si y solo si se pasa exactamente un array. Si se pasa más de un array, el array devuelto tendrá claves secuenciales de tipo integer.

Ejemplo #5 array_map() - con claves de tipo string

<?php
$arr 
= array("stringkey" => "value");
function 
cb1($a) {
    return array (
$a);
}
function 
cb2($a$b) {
    return array (
$a$b);
}
var_dump(array_map("cb1"$arr));
var_dump(array_map("cb2"$arr$arr));
var_dump(array_map(null,  $arr));
var_dump(array_map(null$arr$arr));
?>

El resultado del ejemplo sería:

array(1) {
  ["stringkey"]=>
  array(1) {
    [0]=>
    string(5) "value"
  }
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}
array(1) {
  ["stringkey"]=>
  string(5) "value"
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}

Ver también

  • array_filter() - Filtra elementos de un array usando una función de devolución de llamada
  • array_reduce() - Reduce iterativamente un array a un solo valor usando una función llamada de retorno
  • array_walk() - Aplicar una función proporcionada por el usuario a cada miembro de un array

chreekat

14 years ago

I was miffed that array_map didn't have a way to pass values *and* keys to the callback, but then I realized I could do this:

function callback($k, $v) { ... }

array_map( "callback", array_keys($array), $array);

mail at markuszeller dot com

2 years ago

Thanks to the new lambda function shorthand, you can compact the first example calculating cubic values, which is much nicer to read.

You do not have to declare a function.

$a = [1, 2, 3, 4, 5];
$b = array_map(fn($n) => $n * $n * $n, $a);
print_r($b);

virtual dot greg at gmail dot com

12 years ago

PHP 5.3 enables us to use inline anonymous functions with array_map, cleaning up the syntax slightly.

<?php
$data
= array(
        array(
'id' => 1, 'name' => 'Bob', 'position' => 'Clerk'),
        array(
'id' => 2, 'name' => 'Alan', 'position' => 'Manager'),
        array(
'id' => 3, 'name' => 'James', 'position' => 'Director')
);
$names = array_map(
        function(
$person) { return $person['name']; },
       
$data
); print_r($names);
?>

This was possible (although not recommended) in prior versions of PHP 5, via create_function().

<?php
$names
= array_map(
       
create_function('$person', 'return $person["name"];'),
       
$data
);
?>

You're less likely to catch errors in the latter version because the code is passed as string arguments.

These are alternatives to using a foreach:

<?php
$names
= array();

foreach (

$data as $row) {
       
$names[] = $row['name'];
}
?>

lukasz dot mordawski at gmail dot com

8 years ago

Let's assume we have following situation:

<?php
class MyFilterClass {
    public function
filter(array $arr) {
        return
array_map(function($value) {
            return
$this->privateFilterMethod($value);
        });
    }

    private function

privateFilterMethod($value) {
        if (
is_numeric($value)) $value++;
        else
$value .= '.';
    }
}
?>

This will work, because $this inside anonymous function (unlike for example javascript) is the instance of MyFilterClass inside which we called it.
I hope this would be useful for anyone.

php/hotblocks/nl

10 years ago

Note that the $arr argument has to be an array, not just a Traversable/Iterator.

For instance this won't work:

<?php

$documents

= $mongo->db->collection->find();
// $documents is Traversable by foreach$ids = array_map(function($document) {
  return
$document['_id'];
},
$objects);
// $ids will now be NULL, because $documents wasn't an Array?>

A solution is to first use iterator_to_array():

<?php

$ids

= array_map(function($document) {
  return
$document['_id'];
},
iterator_to_array($objects));
// $ids will now be an array of ['_id']s?>

But this is not very efficient: two cycles instead of one. Another solution is to use foreach: one cycle and a lot of freedom (and in the same scope).

luis at lpdeveloper dot com dot br

2 years ago

ExampleArrow function php >= 7.4
Short closures, also called arrow functions, are a way of writing shorter functions in PHP. This notation is useful when passing closures to functions like array_map or array_filter

<?php
$request
= [
  [
'value'=>1],
  [
'value'=>2],
  [
'value'=>3],
];
print_r(
      
array_map(fn(array $value)=>$value['value'],$request)
);
?>

Output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

radist-hack at yandex dot ru

13 years ago

To transpose rectangular two-dimension array, use the following code:

array_unshift($array, null);
$array = call_user_func_array("array_map", $array);

If you need to rotate rectangular two-dimension array on 90 degree, add the following line before or after (depending on the rotation direction you need) the code above:
$array = array_reverse($array);

Here is example:

<?php
$a
= array(
  array(
1, 2, 3),
  array(
4, 5, 6));
array_unshift($a, null);
$a = call_user_func_array("array_map", $a);
print_r($a);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 4
        )

    [1] => Array
        (
            [0] => 2
            [1] => 5
        )

    [2] => Array
        (
            [0] => 3
            [1] => 6
        )

)

galenjr at gmail dot com

13 years ago

Another way to array_map htmlentities with a specific quote style is to create a function that does it and map that function

<?phpfunction map_entities( $str ) {
    return
htmlentities( $str, ENT_QUOTES );
}
$good_array = array_map ( 'map_entities', $bad_array );?>

CertaiN

7 years ago

Simplest array_map_recursive() implemention.

<?php
function array_map_recursive(callable $func, array $array) {
    return
filter_var($array, \FILTER_CALLBACK, ['options' => $func]);
}
?>

stijnleenknegt at gmail dot com

14 years ago

If you want to pass an argument like ENT_QUOTES to htmlentities, you can do the follow.

<?php
$array
= array_map( 'htmlentities' , $array, array_fill(0 , count($array) , ENT_QUOTES) );
?>

The third argument creates an equal sized array of $array filled with the parameter you want to give with your callback function.

mcmurphy510 at gmail dot com

6 years ago

If you are using Namespaces, the array_map callback expects the Fully Qualified NameSpace to be used.

For example, this won't work:
<?php
namespace Test;
function
mapping_function($var)  {
    ...
}
array_map('mapping_function', $array);  //won't find 'mapping_function' here.
?>

This, however, will work:
<?php
namespace Test;
function
mapping_function($var)  {
    ...
}
array_map('Test\mapping_function', $array);  //using FQNS.
?>

Mahn

6 years ago

You may be looking for a method to extract values of a multidimensional array on a conditional basis (i.e. a mixture between array_map and array_filter) other than a for/foreach loop. If so, you can take advantage of the fact that 1) the callback method on array_map returns null if no explicit return value is specified (as with everything else) and 2) array_filter with no arguments removes falsy values.

So for example, provided you have:

<?php
$data
= [
    [
       
"name" => "John",
       
"smoker" => false
   
],
    [
       
"name" => "Mary",
       
"smoker" => true
   
],
    [
       
"name" => "Peter",
       
"smoker" => false
   
],
    [
       
"name" => "Tony",
       
"smoker" => true
   
]
];
?>

You can extract the names of all the non-smokers with the following one-liner:

<?php
$names
= array_filter(array_map(function($n) { if(!$n['smoker']) return $n['name']; }, $data));
?>

It's not necessarily better than a for/foreach loop, but the occasional one-liner for trivial tasks can help keep your code cleaner.

elfe1021 at gmail dot com

8 years ago

Find an interesting thing that in array_map's callable function, late static binding does not work:
<?php
class A {
    public static function
foo($name) {
        return
'In A: '.$name;
    }

    public static function

test($names) {
        return
array_map(function($n) {return static::foo($n);}, $names);
    }
}

class

B extends A{
    public static function
foo($name) {
        return
'In B: '.$name;
    }
}
$result = B::test(['alice', 'bob']);
var_dump($result);
?>

the result is:
array (size=2)
  0 => string 'In A: alice' (length=11)
  1 => string 'In A: bob' (length=9)

if I change A::test to
<?php
   
public static function test($names) {
        return
array_map([get_called_class(), 'foo'], $names);
    }
?>

Then the result is as expected:
array (size=2)
  0 => string 'In B: alice' (length=11)
  1 => string 'In B: bob' (length=9)

contato at williamsantana dot com dot br

9 years ago

In case of you need to recursively bypass a function over the itens of an array, you can use it

<?php
   
function array_map_recursive($callback, $array) {
        foreach (
$array as $key => $value) {
            if (
is_array($array[$key])) {
               
$array[$key] = array_map_recursive($callback, $array[$key]);
            }
            else {
               
$array[$key] = call_user_func($callback, $array[$key]);
            }
        }
        return
$array;
    }
?>

-----------------------------------------------------------------------

<?php
    $strings
= array(
       
'The',
        array(
           
'quick',
           
'fox',
            array(
               
'brown',
               
'jumps',
                array(
                   
'over',
                    array(
                       
'the',
                        array(
                           
'lazy',
                            array(
                               
'dog'
                           
)
                        )
                    )
                )
            )
        )
    );
print_r($strings);
   
$hashedString = array_map_recursive('md5', $strings);
   
print_r($hashedString);
?>

------------------------------------------------------------------------
Testing it, you'll obtain

<?php/* Original array */array (
 
0 => 'The',
 
1 =>
  array (
   
0 => 'quick',
   
1 => 'fox',
   
2 =>
    array (
     
0 => 'brown',
     
1 => 'jumps',
     
2 =>
      array (
       
0 => 'over',
       
1 =>
        array (
         
0 => 'the',
         
1 =>
          array (
           
0 => 'lazy',
           
1 =>
            array (
             
0 => 'dog',
            ),
          ),
        ),
      ),
    ),
  ),
);
/* Recursived array */
array (
 
0 => 'a4704fd35f0308287f2937ba3eccf5fe',
 
1 =>
  array (
   
0 => '1df3746a4728276afdc24f828186f73a',
   
1 => '2b95d1f09b8b66c5c43622a4d9ec9a04',
   
2 =>
    array (
     
0 => '6ff47afa5dc7daa42cc705a03fca8a9b',
     
1 => '55947829059f255e4ba2f536a2ae99fe',
     
2 =>
      array (
       
0 => '3b759a9ca80234563d87672350659b2b',
       
1 =>
        array (
         
0 => '8fc42c6ddf9966db3b09e84365034357',
         
1 =>
          array (
           
0 => '0ffe34b4e04c2b282c5a388b1ad8aa7a',
           
1 =>
            array (
             
0 => '06d80eb0c50b49a509b49f2424e8c805',
            ),
          ),
        ),
      ),
    ),
  ),
);
?>

Hope it helps you.

Cheers.

pmf

14 years ago

This function behaves exactly like array_map but additionally does not reject non-array arguments. Instead, it transforms them with the array_fill function to a constant valued array of required length according to the other array arguments (if any) and executes the original array_map function.

<?phpfunction array_map2() {
   
$args = func_get_args();$callback = array_shift($args);$args = array_map(
           
create_function('$a,$max','return is_array($a)? $a: array_fill(0,$max,$a);'),
           
$args,array_fill(0,count($args),array_reduce($args,
           
create_function('$v,$w','return max($v,is_array($w)? count($w): 1);'))));array_unshift($args,$callback);

        return

call_user_func_array("array_map",$args);
}
?>

Example:

<?php

$get

= "first=value1&second=value2&third=value3";print_r(array_map2("explode","=",explode("&",$get)));?>

would print out:

<?phpArray
(
    [
0] => Array
        (
            [
0] => first
           
[1] => value1
       
)

    [

1] => Array
        (
            [
0] => second
           
[1] => value2
       
)

    [

2] => Array
        (
            [
0] => third
           
[1] => value3
       
)
)
?>

/pmf

shakespeare32 at gmail dot com

9 years ago

Why not an array of callbacks?

<?php
function array_maps($callbacks, $array) {
    if (!
$callbacks) { return $array; }

        if (!

is_array($callbacks) && is_string($callbacks) && function_exists($callbacks)) {
        return
array_map($callbacks, $array);
    }

    foreach(

$callbacks as $callback) {
        if (
function_exists($callback)) {
       
$array = array_map($callback, $array);
        }
    }

    return

$array;
}
?>

CertaiN

9 years ago

The most memory-efficient array_map_recursive().

<?php
function array_map_recursive(callable $func, array $arr) {
   
array_walk_recursive($arr, function(&$v) use ($func) {
       
$v = $func($v);
    });
    return
$arr;
}
?>

mark at grooveshark dot com

7 years ago

If you're looking for a way to get a specific set of key values (ala "pluck") you can just use array_column([['id' => 1]], 'id').

loaded67 at hotmail dot com

14 years ago

this function is really nice for recursion in php!!!

example in a class:

<?php
class test{//private $container = array();final public function add($key, $value){
        
/* recursion */
        
if(is_array($value)){
              
array_map(array($this, __FUNCTION__), array_keys($value), array_values($value));
         }
        
/* procedural */
        
else{
             echo
$key.' => '.$value.'<br/>'.PHP_EOL;
            
// do stuff...
             // if(!isset($this->container[$key])){
             //       $this->container[$key] = $value;
             // }
             //else{  // trigger_error() xor throw new Exception?
             //         echo 'allready exists!<br/>'.PHP_EOL;
             //}
        
}
    }
}
//
$array = array (
                              
'one'   => 'value1',
                              
'two'   => 'value2',
                              
'three' => 'value3'
                           
);$t = new test;
$t->add($array);
?>

you could easiely do this without a class too offcourse!
used in php 5.2.5

qeremy

10 years ago

An alternative for recursive mapping;

<?php
function array_map_recursive($fn, $arr) {
   
$rarr = array();
    foreach (
$arr as $k => $v) {
       
$rarr[$k] = is_array($v)
            ?
array_map_recursive($fn, $v)
            :
$fn($v); // or call_user_func($fn, $v)
   
}
    return
$rarr;
}

function

sqr($x) {
    return
"$x ^ 2 = ". ($x * $x);
}
$a = array(1, 2, 3, array(4, array(5)));
$b = array_map_recursive("sqr", $a);
print_r($b);
?>

Array
(
    [0] => 1 ^ 2 = 1
    [1] => 2 ^ 2 = 4
    [2] => 3 ^ 2 = 9
    [3] => Array
        (
            [0] => 4 ^ 2 = 16
            [1] => Array
                (
                    [0] => 5 ^ 2 = 25
                )

        )

)

gmail.com@mspreij

10 years ago

Hope I'm not late to the party, here's my function to apply array_map to the *keys* of an array.
Extra array arguments will be used for the callback function's parameters just like with array_map, with the difference that a string is also allowed: it will just be used to create an array of appropriate length with as each value that string. Arrays are left alone (and will be padded with nulls by array_map as needed).

<?php//_________________________________________________
// array_map_keys($callback, $array, [$args, ..]) /
function array_map_keys($callback, $array /* [, $args ..] */) {
 
$args = func_get_args();
  if (!
is_callable($callback)) trigger_error("first argument (callback) is not a valid function", E_USER_ERROR);
  if (!
is_array($array)) trigger_error("second argument must be an array", E_USER_ERROR);
 
$args[1] = array_keys($array);
 
// If any additional arguments are not arrays, assume that value is wanted for every $array item.
  // array_map() will pad shorter arrays with Null values
 
for ($i=2; $i < count($args); $i++) {
    if (!
is_array($args[$i])) {
     
$args[$i] = array_fill(0, count($array), $args[$i]);
    }
  }
  return
array_combine(call_user_func_array('array_map', $args), $array);
}
// Some examples:$arr = array('foo'=>123, 'bar'=>456);// simply uppercase keys:
var_dump(array_map_keys('strtoupper', $arr));
// or..
var_dump(array_map_keys(function($input) {return strtoupper($input);}, $arr));
// >> array(2) { ["FOO"]=>int(123) , ["BAR"]=> int(456) }

// Add a prefix 'myvar_':

var_dump(array_map_keys(function($input, $prefix) {return $prefix.$input;}, $arr, 'myvar_'));
// >> array(2) { ["myvar_foo"]=>int(123) , ["myvar_bar"]=>int(456) }

// Apart from the (static string) prefix, we also number them:

$arr = array('foo'=>123, 'bar'=>456, 'bazz'=>789, 'yadda'=>'0AB');
var_dump(array_map_keys(function($input, $middle, $number) {return $number.':'.$middle.$input;}, $arr, 'myvar_', range(1, count($arr))));
// >> array(4) { ["1:myvar_foo"]=>int(123) , ["2:myvar_bar"]=>int(456) , ["3:myvar_bazz"]=>int(789) , ["4:myvar_yadda"]=>string(3) "0AB" }?>

niemans at pbsolo dot nl

1 year ago

A simple one-liner to add line numbers to a text:

$i = 1; join(" \n", array_map(function($a) use(&$i) { return $i++ . ': '. $a; }, explode(“\n", $text)));

shaman_master at list dot ru

2 years ago

Short-hands to "array_map", fill parameter arrays:
<?php
/**
* Applies the callback to the values of the given list. Mix `array_map()` and `iterator_apply()`.
*
* @param callable $callback Callback function to run for each value in list.
* @param array $parameters Callback parameters, contain the keys "values" and "keys"(optional, auto fill).
* @return array
*/
function arr_map(?callable $callback, array $parameters): array
{
    if (empty(
$parameters['values'])) {
        throw new \
InvalidArgumentException('Parameters must contain the key "values"');
    }
    if (! \
is_iterable($parameters['values'])) {
        throw new \
InvalidArgumentException('Parameter "values" must be iterable');
    }

    if (\

is_object($parameters['values'])) {
       
$parameters['values'] = \iterator_to_array($parameters['values']);
    }
   
$keys = \array_keys($parameters['values']);
    \
array_walk(
       
$parameters,
        function (&
$value, $key) use ($keys) {
            if (
$key == 'keys') {
               
$value = $keys;
            } elseif (
$key != 'values') {
               
$value = \array_fill_keys($keys, $value);
            }
        }
    );
    return \
array_map($callback, ...\array_values($parameters));
}
?>
Usage, add prefix to values:
<?php
$array
= range('a', 'z');
$result = arr_map('sprintf', ['prefix_%s', 'value' => $array]));
$iterator = new ArrayIterator($array);
$result2 = arr_map('sprintf', ['prefix_%s', 'values' => $iterator]);
?>

amolocaleb at gmail dot com

3 years ago

Simple obvious thing to keep in mind:
the number of arrays passed as arguments to an array_map() function should correspond to the number of parameters defined in the callback otherwise,say if you write a function with n parameters and supply m arrays to the array_map  such that m>n,array_map() ignores params at n+1 onwards. but no error or notice is issued. Of course supplying fewer arguments than declared in the function declaration throws an
ArgumentCountError

wapinet at mail dot ru

8 years ago

PHP 5.5.14
<?php
$columns
= range(1, 100000);
$time = microtime(true);/*
0.067003011703491 sec
24903680 byte
*/
array_map(function ($value) {
    return
'p.' . $value;
},
$columns);/*
0.042001962661743 sec
19398656 byte
*/
foreach ($columns as $key => $column) {
   
$columns[$key] = 'p.' . $column;
}
/*
0.05500316619873 sec
10747904 byte
*/
array_walk($columns, function (&$value, $key) {
   
$value = 'p.' . $value;
});
/*
0.0260009765625 sec
10747904 byte
*/
foreach ($columns as &$column) {
   
$column = 'p.' . $column;
}

echo

microtime(true) - $time . "\n" . memory_get_peak_usage(true) . "\n";

jessiedeer at hotmail dot com

9 years ago

array_map becomes interesting and faster than foreach when used with existing PHP functions.

Example:

$arr1 = array(1, 2, 3, 4);
$arr2 = array(4, 3, 2, 1);

// array with min values for each key
print_r(array_map("min", $arr1, $arr2));

Result: Array ( [0] => 1 [1] => 2 [2] => 2 [3] => 1 )

// array with max values for each key
print_r(array_map("max", $arr1, $arr2));

Result: Array ( [0] => 4 [1] => 3 [2] => 3 [3] => 4 )

onassar at gmail dot com

12 years ago

Fixed a bug with array recursion.

<?php
       
/**
         * arrayMap function. Customized array_map function which preserves keys/associate array indexes. Note that this costs a descent amount more memory (eg. 1.5k per call)
         *
         * @access public
         * @param callback $callback Callback function to run for each element in each array.
         * @param mixed $arr1 An array to run through the callback function.
         * @param array $array Variable list of array arugments to run through the callback function.
         * @return array Array containing all the elements of $arr1 after applying the callback function to each one, recursively, maintain keys.
         */
       
function arrayMap($callback,$arr1) {
           
$results       =    array();
           
$args          =    array();
            if(
func_num_args()>2)
               
$args          =    (array) array_shift(array_slice(func_get_args(),2));
            foreach(
$arr1 as $key=>$value) {
               
$temp    =    $args;
               
array_unshift($temp,$value);
                if(
is_array($value)) {
                   
array_unshift($temp,$callback);
                   
$results[$key]    =    call_user_func_array(array('self','arrayMap'),$temp);
                } else {
                   
$results[$key]    =    call_user_func_array($callback,$temp);
                }
            }
            return
$results;
        }
?>

stephen at mu dot com dot au

19 years ago

A note when doing something allong the lines of:

<?php
class foo {
  var
$var;
  function
bar() {
    
array_map(array($this, "baz"), array(1,2,3));
  }

  function

baz($arg) {
   
$this->var = $this->var + $arg;
  }
}
?>

This will *not* work as expected. You need to pass $this by reference as with:

array_map(array(&$this, "baz"), array(1,2,3));

or you'll be making a copy of the object each time, changing a value, then throwing the result away.

lewiscowles at me dot com

5 years ago

The words "is an immutable implementation" are missing...

Essentially the collection you send in can be sent to the same var you operate after map has completed, thus explicitly overwriting, but importantly the input array is not modified, so the method is (as it should be) immutable. This means if you send in `$array1` and assign result to `$array2`, you'll still have `$array1` as it was prior to the map function call.

This is entirely separate from foreach modification semantics where mostly I've seen a mix of immutable (assigning to a new object) and mutable (using key and array to update in-place `$arrayinput[$key] = doSomethingWith($value)`.

This is not a comment on the internal workings but has been tested on 5.4, 5.6, 7.0 and 7.1

jessiedeer at hotmail dot com

9 years ago

array_map becomes interesting and faster than foreach when used with existing PHP functions.

Example:

$arr1 = array(1, 2, 3, 4);
$arr2 = array(4, 3, 2, 1);

// array with min values for each key
print_r(array_map("min", $arr1, $arr2));

Result: Array ( [0] => 1 [1] => 2 [2] => 2 [3] => 1 )

// array with max values for each key
print_r(array_map("max", $arr1, $arr2));

Result: Array ( [0] => 4 [1] => 3 [2] => 3 [3] => 4 )