ID: 24980 Updated by: [EMAIL PROTECTED] Reported By: cjbj at hotmail dot com -Status: Assigned +Status: Closed Bug Type: Arrays related Operating System: Windows 2000 PHP Version: 4.3.2 Assigned To: iliaa New Comment:
This bug has been fixed in CVS. In case this was a PHP problem, snapshots of the sources are packaged every three hours; this change will be in the next snapshot. You can grab the snapshot at http://snaps.php.net/. In case this was a documentation problem, the fix will show up soon at http://www.php.net/manual/. In case this was a PHP.net website problem, the change will show up on the PHP.net site and on the mirror sites in short time. Thank you for the report, and for helping us make PHP better. Previous Comments: ------------------------------------------------------------------------ [2003-08-08 03:19:40] cjbj at hotmail dot com 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. ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=24980&edit=1
