note 97413 added to function.array-reduce

From: Date: Sun, 18 Apr 2010 22:30:09 +0000
Subject: note 97413 added to function.array-reduce
Groups: php.notes 
Request: Send a blank email to php-notes+get-168382@lists.php.net to get a copy of this message
It seems that $initial is a required value; if you do not provide $initial, the first value used in the iteration is NULL. Perhaps this is not a problem for callback functions that treat NULL as an identity (e.g. addition), but is a problem for cases when NULL is not identity (such as boolean context). Compare: <?php function andFunc($a,$b) { return $a&&$b; } $foo=Array(true,true,true); var_dump(array_reduce($foo,"andFunc")); ?> returns false! One would expect that it would return true because true&&true&&true == true! Adding diagnostic output to andFunc() shows that the first call to andFunc is with the arguments (NULL,true). This resolves to false (as (bool)null == false) and thereby corrupts the whole reduction. So in this case I have to set $initial=true so that the first call to andFunc() will be (true,true). Now, if I were doing, say, orFunc(), I would have to set $initial=false. Beware. Note that the "rmul" case in the example sneakily hides this defect! They use an $initial of 10 to get 10*1*2*3*4*5=12000. So you would assume that without an initial, you would get 1200/10 = 120 = 1*2*3*4*5. Nope! You get big fat zero, because int(null)==0, and 0*1*2*3*4*5 = 0! I don't honestly see why array_reduce starts with a null argument. The first call to the callback should be with arguments ($initial[0],$initial[1]) [or whatever the first two array entries are], not (null,$initial[0]). That's what one would expect from the description. Incidentally this also means that under the current implementation you will incur count($input) number of calls to the callback, not count($input)-1 as you might expect. ---- Server IP: 192.41.40.227 Probable Submitter: 174.46.204.200 ---- Manual Page -- http://www.php.net/manual/en/function.array-reduce.php Edit -- https://master.php.net/note/edit/97413 Del: integrated -- https://master.php.net/note/delete/97413/integrated Del: useless -- https://master.php.net/note/delete/97413/useless Del: bad code -- https://master.php.net/note/delete/97413/bad+code Del: spam -- https://master.php.net/note/delete/97413/spam Del: non-english -- https://master.php.net/note/delete/97413/non-english Del: in docs -- https://master.php.net/note/delete/97413/in+docs Del: other reasons-- https://master.php.net/note/delete/97413 Reject -- https://master.php.net/note/reject/97413 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#168382) next »