0

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?

3
  • So how can i get the result=318.6? thanks Commented Sep 29, 2011 at 9:41
  • 3
    You will get the result 318.6 with $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; Commented Sep 29, 2011 at 9:45
  • $arr = array(1,2,3,4,5,6); $initial = array_shift($arr); $result = array_reduce($arr, create_function('$op1,$op2','return $op1=-$op2;'),$initial); echo $result; Commented Sep 29, 2011 at 14:01

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Why a down vote on this? This is the answer. On the first function call it will be null -= 321 which will result to -321, then on the consequent calls it will be -321 -= 0.4, ...
2

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

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

Comments

0

Try...

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

and all should become clear.

Comments

0

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;

2 Comments

$arr = array(1,2,3,4,5,6); $initial = array_shift($arr); $result = array_reduce($arr, create_function('$op1,$op2','return $op1=-$op2;'),$initial); echo $result; I need something like ((((1-2)-3)-4)-5)-6 = -19, but result above is not the same like what i need, please kindly help me. Thanks
You have an error in your statement. $op1=-$op2 should be $op1-=$op2. The -= means "take left, substract right and save to left" while =- only means "save negative of right to left".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.