Having read this SO post, In PHP I am aware that you can get the index
under iteration with array_map
as such:
array_map(function($item, $index) { ... }, $items, array_keys($items));
How can I get the an $index
available to me when I use array_reduce
? I have tried:
array_reduce($items, array_keys($items), function($acc, $item, $index) { ... }, array());
array_reduce($items, function($acc, $item, $index) { ... }, array(), array_keys($items));
But I still can't seem to get $index
in an array_reduce
. Has anyone successfully done this before?
EDIT
Here's some context as to why I am asking this question.
I do not want to use foreach
because I would have to mutate an array outside of the foreach
in order to create my collection. I would prefer to avoid mutation.
Other languages allow one to use reduce
and get access to the current index like in JavaScript and Ruby. I was hoping to get the same feature in PHP. Oh well! Looks like I'm going to have to use a foreach
to create my array while also having the current index under iteration.