I have a list of five numbers echoed by php as demonstrated below:-
<div id="items">
<span class="number" id="one"><?php echo $one; //result = 1?> </span>
<span class="number" id="two"><?php echo $two; //result = 2?> </span>
<span class="number" id="three"><?php echo $three; //result = 3?> </span>
<span class="number" id="four"><?php echo $four; //result = 4?> </span>
<span class="number" id="five"><?php echo $five; //result = 5?> </span>
<div id="result"></div>
</div>
I would like to have a result of the best three scores displayed in the <div id="result"></div>
div
For instance, in my question i would expect my result to be 12
I there a simple way of doing this. probably with javascript or even PHP?
<?php
$arr = array($one,$two,$three,$four,$five);
arsort($arr); // sort descending, highest first
$tre = array_slice($arr, 0, 3); // first three
$sum = array_sum($tre); // summed up
?>
<div id="result"><?php echo $sum; ?></div>
Dump them into an array. Sort the array. Add up the top 3.
var nums = [<? echo $one ?>,<? echo $two ?>,<? echo $three ?>,<? echo $four ?>,<? echo $five ?>]
nums.sort()
var resultIs = nums[2]+nums[3]+nums[4];
document.getElementById("result").innerHTML = resultIs;
It's necessary to sort the array because you only want the 3 best. This way you can send them in in any order, and you will easily find the ones you want.
This is what I would do:
$nums = [$one, $two, $three, $four, $five];
sort($nums);
$last_three = array_slice($nums, -3);
$result = array_sum($last_three);
echo $result;
Javascript only solution, no PHP
var sum = Array.prototype.map.call(
document.querySelectorAll("span.number"),
function(element) {
return parseInt(element.innerHTML, 10);
}
).sort(function(a, b) {
return b - a
}).slice(0,3).reduce(function(sum, newValue) {
return sum + newValue
}, 0);
document.querySelector("div#result").innerHTML = sum;