Search code examples
phparray-map

Looking for function similar to array_map but which the same arg each time to the callback


As someone who is learning PHP I was experimenting with the arrap_map function. I was hoping that it would pass the same 3rd arg each time through to the called function. As below, this is not the behaviour of array_map. Is there an alternative function I can use to achieve this?

$arr = [['a'], ['b'], ['c']];
$args = ['set'];

function mapper($item, $arg){
return $item[] = $arg;
}
$result = array_map('mapper', $arr, $args);

only the first element has 'set' as a value

 $arr = [['a'], ['b'], ['c']];
$args = ['set', 'set', 'set'];

function mapper($item, $arg){
return $item[]  = $arg;
}

$result = array_map('mapper', $arr, $args);

all three elements have 'set' as a value


Solution

  • Your code is incorrect, $a[$b] doesn't make any sense. Both variables are strings.

    Your output also doesn't make sense, quoting from the manual:

    If more than one argument is passed then the returned array always has integer keys.


    To answer your question, it's a language design choice.

    It could

    • pass NULL for missing elements (that was PHP does).
    • throw an error if the inputs don't have the same size.
    • cycle the smaller inputs.

    All these have valid applications and their own problems.