Nabi Nabi - 1 year ago 174
PHP Question

Php array subtract values

I have following array:


I wanna subtract all values on array

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


Something like
but unlike !

Answer Source

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;


$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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download