|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2013-04-22 19:41 UTC] jdoane at vlacs dot org
Description:
------------
When array_reduce is called with an object as the third argument, the variable
passed to said third argument will turn into the result of the array_reduce()
call. It feels like the object getting passed into array_reduce is not being
cloned and is being modified in place. Since all objects are passed as a reference
it changes the "$initial" variable in the scope where array_reduce was called.
So either documentation needs to be updated that says that $initial gets set to
the return value when it is an object or this shouldn't happen to begin with as it
appears that $initial should remain immutable for the duration of the
array_reduce() call.
Test script:
---------------
$array = (object)Array('foo', 'baraz');
$initial = (object)Array('count' => 0, 'maxlen' => 0);
$output = array_reduce($array, function(&$d, $item) {
if($d->maxlen < strlen($d)) { $d->maxlen = strlen($d); }
$d->count++;
return $d;
}
print_r($output);
print_r($initial);
Expected result:
----------------
~$ php test.php
stdClass Object
(
[count] => 0
[maxlen] => 0
)
stdClass Object
(
[count] => 2
[maxlen] => 5
)
Actual result:
--------------
~$ php test.php
stdClass Object
(
[count] => 2
[maxlen] => 5
)
stdClass Object
(
[count] => 2
[maxlen] => 5
)
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Dec 03 05:00:01 2025 UTC |
The order of the expected output is backwards, I apologize. It should be: ~$ php test.php stdClass Object ( [count] => 2 [maxlen] => 5 ) stdClass Object ( [count] => 0 [maxlen] => 0 )