|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull Requests
Pull requests:
HistoryAllCommentsChangesGit/SVN commits
[2013-10-09 22:20 UTC] php at hotblocks dot nl
-Summary: array_reduce() callback should receive current key
+Summary: array_reduce() callback should receive current
key/index
[2013-10-09 22:20 UTC] php at hotblocks dot nl
[2014-09-27 10:52 UTC] cameron dot adam+php at gmail dot com
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Nov 02 19:00:02 2025 UTC |
Description: ------------ In most languages, the callback of Array's reduce() method receives the current index (as well as $result and $item). In PHP it doesn't. There's plenty of room for a third argument, since it's never used. The test script assumes that 3rd argument. Test script: --------------- // Compare string lengths and remember index of the longest. $strings = ['foo', 'bar', 'fooo', 'barry', 'barrr']; $longest_index = array_reduce($strings, function($result, $string, $index) use ($strings) { return strlen($string) > strlen($strings[$result]) ? $index : $result; }, 0); // Re-key array depending on values. $array = ['10' => 'a', '20' => 'b', '150' => 'c']; $rekeyed = array_reduce($array, function($result, $el, $index) { $new_index = $el > 100 ? 'x' . $index : 'y' . $index; $result[$new_index] = $el; return $result; }, []); Expected result: ---------------- I expect $index in the callbacks to be present, and: $longest_index should be 3 (for 'barry'), and $rekeyed should have indexes 'x10', 'x20' and 'y150'. Actual result: -------------- Warnings and nils.