php sum values from array with maximum value

I wanted to get the sum of values and limit them with a maximum value. My maximum value is 500.
My array:
array:11 [
0 => 100
1 => 100
2 => 100
3 => 100
4 => 100
5 => 100
6 => 300
7 => 300
8 => 300
9 => 300
10 => 300
11 => 300
12 => 300
13 => 300
14 => 300
15 => 300
]
So each 100 will be sum up to 500 and end up getting this array below.
Desired output:
array:11 [
0 => 300
1 => 300
2 => 300
3 => 300
4 => 300
5 => 300
6 => 300
7 => 500
8 => 500
9 => 500
]
This is what I did so far. Tried to sort all numbers from lowest to highest usingusort
.
usort($orderSumArr, function ($a, $b) {
return $a > $b;
});
$sumArr = [];
$current = 0;
foreach ($sumArr as $num) {
if ($current + $num <= 500) { // limit up to 500
$current += $num;
} else {
$sumArr[] = $current;
$current = $num;
}
}
$sumArr[] = $currentSum2;
And this is the output I'm getting. It ends up adding the first 100 which produce 500 and the remaining 100 was added to 300 which sum up to 400.
array:11 [
0 => 300
1 => 300
2 => 300
3 => 300
4 => 300
5 => 300
6 => 300
7 => 300
8 => 300
9 => 400
10 => 500
]
Thanks in advance!!
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: php_network_getaddresses: getaddrinfo failed: temporary failure in name resolution
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.