Why does array_map () with a null callback create an "array of arrays"?

Today I found out about the special case of array_map() in PHP, which is referred to as a note in the documentation:

Example # 4 Creating an Array of Arrays

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

The above example outputs:

 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 ) ) 

If the array argument contains string keys, then the returned array will contain string keys if and only if exactly one array is passed. If multiple arguments are passed, the returned array always has integer keys.

(try it)

But this. No more explanation. I understand that this does the same thing as

 $d = array_map(function() { return func_get_args(); }, $a, $b, $c); 

But why would anyone want or expect this to be the default behavior? Is there a technical reason why it works as a side effect of the implementation? Or is it just a random β€œlet's do this function do one more” solution (looking at you, array_multisort() )?

+7
arrays php specifications array-map
source share
1 answer

This is apparently a special case in _array_map_, but it is only documented in this example. NULL is usually not allowed as a callback (if you try to use it with call_user_func() , it reports an error), but it is allowed in _array_map () _. It treats NULL as meaning that it should just create an array of arguments.

This is useful because array also invalid as a callback, because it is a language, not a function. Therefore, you cannot write:

 $d = array_map('array', $a, $b, $c); 
+2
source share

All Articles