Req #65872 [Opn]: array_reduce() callback should receive current key/index

From: Date: Wed, 09 Oct 2013 22:20:33 +0000
Subject: Req #65872 [Opn]: array_reduce() callback should receive current key/index
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-182107@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=65872&edit=1 ID: 65872 User updated by: php at hotblocks dot nl Reported by: php at hotblocks dot nl -Summary: array_reduce() callback should receive current key +Summary: array_reduce() callback should receive current key/index Status: Open Type: Feature/Change Request Package: Arrays related Operating System: All PHP Version: Irrelevant Block user comment: N Private report: N New Comment: Summary+ Previous Comments: ------------------------------------------------------------------------ [2013-10-09 22:18:29] php at hotblocks dot nl 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. ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=65872&edit=1

« previous php.bugs (#182107) next »