Nabi Nabi - 4 months ago 34
PHP Question

Php array subtract values

I have following array:

array(50,6,8,9)


I wanna subtract all values on array

Result must be: (50-6-8-9=equals):

27


Something like
array_sum
but unlike !

Answer

First you have to sort array, just to make sure that highest number is last one in array (otherwise it wont work, results wont be correct). Set starting value of result as last (highest) number of array, then loop through all numbers an subtract all numbers from highest one.

$arr = array(50,6,8,9); 
$arr_len = count($arr)-1;

sort($arr);

$result = $arr[$arr_len];
for ($i = $arr_len-1; $i >= 0; $i--) {
    $result -= $arr[$i];
} 
echo $result;

If you want to subtract all values (no matter which one is highest) then use following code:

$arr = array(50,6,8,9); 
$result = $arr[0];
for ($i = 1; $i < count($arr); $i++) {
    $result -= $arr[$i];
} 
echo $result;
Comments