|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2003-08-08 19:03 UTC] iliaa@php.net
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Oct 30 09:00:02 2025 UTC |
Description: ------------ If the optional 'initial' parameter to array_reduce() is omitted, its default value is the first element of the array, and iteration proceeds over the second and subsequent array elements. This means that the first element may not have the "function" applied to it. Reproduce code: --------------- For example: <?php // See "Programming PHP (O'Reilly, March 2002)" on p128 function add_up($running_total, $current_value) { echo "running_total is $running_total, current_value is $current_value\n"; $running_total += $current_value * $current_value; return $running_total; } $numbers = array (2,3,5,7); $total = array_reduce($numbers, 'add_up'); print "Total is $total\n"; ?> Expected result: ---------------- The expected output is: running_total is 0, current_value is 2 running_total is 4, current_value is 3 running_total is 13, current_value is 5 running_total is 38, current_value is 7 Total is 87 This calls add_up() once per array element. Actual result: -------------- The actual result is: running_total is 2, current_value is 3 running_total is 11, current_value is 5 running_total is 36, current_value is 7 Total is 85 Adding the optional third parameter to array_reduce(): $total = array_reduce($numbers, 'add_up', 0); gives the expected (and desired for the default case) output: running_total is 0, current_value is 2 running_total is 4, current_value is 3 running_total is 13, current_value is 5 running_total is 38, current_value is 7 Total is 87 This total is the sum of the squares. The uncomfirmed errata to Programming PHP (http://www.oreilly.com/catalog/progphp/errata/progphp.unconfirmed) indicates to me the default value of 'initial' may be a bug. If it is not a bug, then the current behavior doesn't seem to match common expectations and the manual entry "applies iteratively the function function to the elements of the array input" could be clarified. Tested on 4.3.2 on Windows 2000 with the prebuilt binary of 29 June 2003 from php.net.