I opened bug #33447 the other day which is a feature request to allow
array_reduce to have a mixed starting value. It currently will only
accept integers which I feel is an odd limitation since the array can
hold any value.
This is a trivial patch to array_reduce which removes this limitation.
All the tests passed with this modification (that passed without it). I
also included a test file which tests the new functionality and provides
a few examples of what it could be useful for.
David
Index: ext/standard/array.c
===================================================================
RCS file: /repository/php-src/ext/standard/array.c,v
retrieving revision 1.304
diff -u -b -w -B -r1.304 array.c
--- ext/standard/array.c 21 Jun 2005 12:10:51 -0000 1.304
+++ ext/standard/array.c 24 Jun 2005 02:40:29 -0000
@@ -3992,7 +3992,7 @@
/* }}} */
-/* {{{ proto mixed array_reduce(array input, mixed callback [, int initial])
+/* {{{ proto mixed array_reduce(array input, mixed callback [, mixed initial])
Iteratively reduce the array to a single value via the callback. */
PHP_FUNCTION(array_reduce)
{
@@ -4027,7 +4027,6 @@
ALLOC_ZVAL(result);
*result = **initial;
zval_copy_ctor(result);
- convert_to_long(result);
INIT_PZVAL(result);
} else {
MAKE_STD_ZVAL(result);
--TEST--
Bug #33447 - array_reduce should have a mixed starting value
--FILE--
<?php
# Array initial value, use to flatten the array
$list = Array( Array("a"), Array("b"), Array("c") );
var_dump( array_reduce($list, 'array_merge', Array()) );
# Int initial value, from docs
function rsum($v, $w)
{
$v += $w;
return $v;
}
function rmul($v, $w)
{
$v *= $w;
return $v;
}
$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", 1);
var_dump($b);
var_dump($c);
var_dump($d);
# String initial value
function str_cat($v, $w) {
return $v.$w;
}
$list = Array("page1", "page2", "page3");
var_dump( array_reduce($list, 'str_cat', '') );
var_dump( array_reduce($list, 'str_cat') );
var_dump( array_reduce($list, 'str_cat', 'hi lod') );
?>
--EXPECT--
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
int(15)
int(1200)
int(1)
string(15) "page1page2page3"
string(15) "page1page2page3"
string(21) "hi lodpage1page2page3"
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php