2

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?

4
  • 2
    Yes, but you have to write it :) Have you tried to write anything yet? Commented Jan 17, 2020 at 10:17
  • 2
    @RiggsFolly Yes I have but unfortunately It would pick the closest number... But I think Qirel fixed my question. Thanks for your time! Commented Jan 17, 2020 at 10:30
  • 1
    What if your answer falls out of the range of numbers in the array? Commented Jan 17, 2020 at 11:12
  • @Progrock with the answer of Qirel it wil take the closest. This is exactly what I needed. (: Commented Jan 17, 2020 at 11:18

3 Answers 3

6

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;
}));
Sign up to request clarification or add additional context in comments.

Comments

-1

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

2 Comments

Except OP is trying to pick a number out of an array?
the array could be any number so this would unfortunatly not work... thanks for your time though!
-1

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;

3 Comments

My question has already been solved. Thanks for taking the time though! This looks like a good alternative
The suggested solution does not find the nearest value it always rounds down... but I am glad if that cover your needs.
You are returning the nearest number in the array, not the lowest nearest. 3v4l.org/0Qfnm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.