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

From: Date: Sat, 27 Sep 2014 10:52:03 +0000
Subject: Req #65872 [Com]: array_reduce() callback should receive current key/index
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-187733@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 Comment by: cameron dot adam+php at gmail dot com Reported by: php at hotblocks dot nl 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: If you were to implement this change (you should, it's a significant shortfall in the implementation, I think), then perhaps follow CFML's lead on these kind of functions. I've written an opinion on this in reaction to a stack overflow question, the solution to which could use array_reduce() nicely if it was implemented better: http://blog.adamcameron.me/2014/09/php-significant-oversight-in.html. I think CFML have nailed these functions well. The conceit is they not only pass the value, they also pass the index, and as well as that a ref to the entire array too (which is, sometimes, very handy to have for cross-entry analysis). I think the CFML approach would still fit in with the general PHP milieu here? Previous Comments: ------------------------------------------------------------------------ [2013-10-09 22:20:33] php at hotblocks dot nl Summary+ ------------------------------------------------------------------------ [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 (#187733) next »