Reputation: 93
I am struggling to get the lowest value based on the answer of the client.
$client_answer = 28;
$array = array(10,20,30,40,50);
The answer that should be given is: 20
So every answer should be rounded down to the lower number.
Other examples:
$client_answer = 37;
$array = array(10,20,30,40,50);
answer should be 30.
$client_answer = 14;
$array = array(10,20,30,40,50);
answer should be 10.
$client_answer = 45;
$array = array(10,20,30,40,50);
answer should be 40.
Is there a php function that I can use for this?
If not how can this be accomplished?
Upvotes: 2
Views: 79
Reputation: 63
Only this rounds correctly
$client_answer = 28;
$array = array(10,20,30,40,50);
rsort($array,1);
$min_diff = max($array);
$closest_val = max($array);
foreach($array as $val)
{
if(abs($client_answer - $val) < $min_diff)
{
$min_diff = abs($client_answer - $val);
$closest_val = $val;
}
}
echo $closest_val;
Upvotes: -1
Reputation: 30
This might be a very stupid answer, but in this specific case, you are trying to truncate the unit number? Why not try this:
$client_answer = intdiv( $client_answer, 10) * 10;
Divide by 10, get rid of the last digit, and multiply again. EDIT : typo
Upvotes: -1
Reputation: 26450
You can filter the array to only contain values equal to or below the given value $client_answer
, then use max()
on the filtered array.
$value = max(array_filter($array, function($v) use ($client_answer) {
return $v <= $client_answer;
}));
Upvotes: 6