this i my array
$arr = array(1,2,3,4,5);
How to get the result that calculate the value of this expression ((((1-2) -3)-4)-5)?
this i my array
$arr = array(1,2,3,4,5);
How to get the result that calculate the value of this expression ((((1-2) -3)-4)-5)?
2 times the first entry minus the whole sum - looks pretty quick.
echo (2 * reset($arr)) - array_sum($arr);
Just substract the sum of all elements but the first from the first element:
echo array_shift($arr) - array_sum($arr); # -13
To preserve the array, change the calculation a little:
echo $arr[0]*2 - array_sum($arr); # -13
And we're glad you didn't ask for eval:
echo eval('return '.implode('-', $arr).';'); # -13
However the best suggestion I can give is that you encapsulate the logic into a class and overload the array with it. So that the object than can provide a method for the calculation (Demo):
class Operands extends ArrayObject
{
public function operate($sign)
{
$sign = max(-1, min(1, $sign.'1'));
$arr = $this->getArrayCopy ();
return $arr[0]*(1-$sign) + $sign*array_sum($arr);
}
public function __invoke($sign) {
return $this->operate($sign);
}
}
$arr = new Operands($arr);
echo $arr('-'), ', ' , $arr('+');
Try this:
$arr = array(1,2,3,4,5);
// load the first number to subtract
$result = $arr[0];
$i = 1;
foreach($arr as $item)
{
if ($i !=1) // skip the first one
$result -= $item;
$i++;
}
echo $result;
?>