开发者

Array Reduce PHP

开发者 https://www.devze.com 2023-04-09 11:43 出处:网络
I have an: $arr = array(321,0.4,0.8,1.2); $result = array_reduce($arr,create_function(\'$op1,$op2\',\'return $op1-=$op2;\'));

I have an :

$arr = array(321,0.4,0.8,1.2);
$result = array_reduce($arr,create_function('$op1,$op2','return $op1-=$op2;'));
echo $result; //the result sh开发者_如何学Pythonould be 318.6, but i got -323.4

would you please tell me what's wrong with this?


The array_reduce function has 3 parameters. The 3rd is $initial.

This is by default NULL. You should fill this one too. Look here: http://nl.php.net/array_reduce

If the optional initial is available, it will be used at the beginning of the process, or as a final result in case the array is empty.


Just substract the sum of all elements but the first from the first element:

echo array_shift($arr) - array_sum($arr); # 318.6


Try...

array_reduce($arr,
       create_function('$op1,$op2','print "$op1, $op2\n"; 
                                    return $op1-=$op2;'));

and all should become clear.


You are using the array_reduce in the wrong way. The first item in the array needs to be shifted out of the array and used as the initial value.

$arr = array(321,0.4,0.8,1.2);
$initial = array_shift($arr);
$result = array_reduce($arr, create_function('$op1,$op2','return $op1-=$op2;'), $initial);
echo $result;
0

精彩评论

暂无评论...
验证码 换一张
取 消