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 should 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.
null -= 321 which will result to -321, then on the consequent calls it will be -321 -= 0.4, ...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;
318.6with$arr = array(321,0.4,0.8,1.2); $result = array_reduce($arr,create_function('$op1,$op2','return $op1-=$op2;'), $arr[0]*2); echo $result;