Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sum up all remaing amount after get max value from array?

Tags:

arrays

php

I hesitated to this question either should I ask or not. I think that this is much more logical question. But, I can't really figure it out.

I have a array that may include

$programFees = [100,200,100,500,800,800]

I can get max value from this array using max($programFees). If I have 2 max value like 800,800, I want to take one only. I realized that php max can solve this.

But, I want to sum up all remaining amount from that array.

e.g

$maxProgramFees = max($programFees); 
//I got 800 and remaining amount is [100,200,100,500,800]

My total amount should be 1700. Which approach should I use to get this amount?

like image 414
502_Geek Avatar asked Dec 07 '17 01:12

502_Geek


2 Answers

Sort the array, grab the largest, then shift the array to get the remainder values. Add those values

<?php 
$programFees = [100, 200, 100, 500, 800, 800];
rsort($programFees); //sort high -> low

$highest = $programFees[0]; // 800
array_shift($programFees); // remove the highest value

$sum = array_sum($programFees); // 1700

rsort() documentation

array_shift() documentation

array_sum() documentation

like image 114
helllomatt Avatar answered Nov 05 '22 19:11

helllomatt


@helllomatt has already provided a very good answer, however, if you cannot modify the array order for some reason you may want to try something like this.

$programFees = [100,200,100,500,800,800];
$maxProgramFees = max($programFees);
$sum = array_sum(array_diff($programFees, array($maxProgramFees)));

I would assume the rsort() answer would be the faster option.

like image 34
Alex Barker Avatar answered Nov 05 '22 19:11

Alex Barker