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?
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
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With