This is the code I currently have:
$required = 1.3;
$stacks = 0;
$remaining = $required;
$whichtakes = [];
$array_result = ['0.6', '0.5', '0.8', '0.7'];
for($i = 0; $i < count($array_result); $i++) {
if($array_result[$i] <= $required && $stacks + $array_result[$i] <= $required) {
$stacks += $array_result[$i];
echo $remaining -= $array_result[$i];
$whichtakes[] = $array_result[$i];
}
}
print_r($whichtakes);
Output is
Array (
[0] => 0.6
[1] => 0.5
)
This is fetching just 0.6 and 0.5 (first two values) and gives a remaining value (the sum is 1.1, so 0.2 is remaining). But the input has 2 values whose sum matches with my $required
value: 0.8 and 0.7.
How can I improve my code so that it will find those values? If there is no exact match possible, I would like to get a series of values whose sum comes as close as possible, minimising the remaining value.