502_Geek
502_Geek

Reputation: 2126

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

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?

Upvotes: 5

Views: 135

Answers (2)

Alex Barker
Alex Barker

Reputation: 4400

@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.

Upvotes: 1

helllomatt
helllomatt

Reputation: 1339

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

Upvotes: 5

Related Questions