There is a function that adds the elements of array_sum.

And I want to do that, which subtracts the elements of the array and I can not.

$arr2 = array(1,2,3,4); function foo2($mass, $znak){ $res = $mass[0]; foreach($mass as $value){ echo $res = $res - $value; }; return $res; }; foo2($arr2); 

If I write 0 to the $ res variable, then immediately it will be subtracted from zero, and I need, first, to subtract 2 from 1.

How to do it?

It should be 1-2-3-4 = -8

And how to do that in a function, you could pass a parameter that decides what to do with the elements? minus plus

    3 answers 3

     function foo2($mass, $znak){ $sum = 0; foreach($mass as $value){ $sum = $sum + $value; } if($znak == '+') return $sum; else return $mass[0] - ($sum - $mass[0]); } 

    It works for me.

    • does not work, does not display anything at all - DivMan
    • Works, forgot to add echo - DivMan

    Add the first element to the result again.

     $arr2 = array(1,2,3,4); function foo2($mass){ $res = $mass[0]; foreach($mass as $value){ $res = $res - $value; }; // 1 - 1 + 1 = 1 return $res + $mass[0]; }; echo foo2($arr2); 

    Another variant. Here you can pass the function to be applied to the array.

     $arr2 = array(1,2,3,4); function sum($carry, $item) { $carry += $item; return $carry; } function sub($carry, $item) { $carry -= $item; return $carry; } // работает только с sub или sum function foo2($mass, $func){ $res = array_reduce($mass, $func, $mass[0]); return call_user_func($func, $res, -$mass[0]); } echo foo2($arr2, "sub"); echo "\n"; echo foo2($arr2, "sum"); 
    • and nothing has changed - DivMan
    • not changed - DivMan
    • I corrected the answer. now everything should work correctly. you can check here ideone.com/VHSO24 - Mikhail Vaysman
    • error gives Parse error: syntax error
    • 145 line return (new MyMath ($ arr)) -> $ methname (); - DivMan
     class MyMath{ private $arr; public function __construct($arr){ $this -> arr = $arr; } public function sum() $res = 0; foreach($this -> arr as $item => $val){ $res += $val; } return $res; } public function subtraction(){ $res = 0; foreach($this -> arr as $item => $val){ $res = $item ? $res - $val : $val; } } } function callMyMath($arr, $methname){ return (new MyMath($arr)) -> $methname(); } // 'sum' or 'subtraction' callMyMath([3,5,6,7], 'sum'); 

    Well, suddenly, if you need a convenient extensible class, then here)