0

I have a range of values in an array like:

$values = array(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5);

I need to find the index of the smallest value in that array that's greater than or equal to a specified number. For example, if the user inputs 0.25, I need to know that the first array index is 2.

In other languages I've used, like R, there is a 'which' function that will return an array of indices that meet some criteria. I've not found that in PHP, so i'm hopeful someone else has solved this.

Thanks.

5 Answers 5

1

You can use array_filter

It does exactly what R which does.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually, you'd then need to call array_keys on the result to get the indices.
0

Hope this function will help you,

function find_closest_item($array, $number) {
    sort($array);
    foreach ($array as $a) {
        if ($a >= $number) return $a;
    }
    return end($array); // or return NULL;
}

Comments

0

I don't know if there's a built in function for that, but this should work:

function getClosest($input, $array) 
{
    foreach($array as $value)
    {
        if ($value >= $input)
        {
            return $value;
        }
    }

    return false;
}

Comments

0

You can use the following working logic. There might be other built in functions which can be used to solve this problem.

<?php
$values = array(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5);
$search=0.35;
$result_index = NULL;
$result_value=NULL;

$count=count($values);
for($i=0;$i<$count;$i++) {
    if($values[$i]<$search) {
        continue;
    }
    if($result_index==NULL) {
        $result_index = $i;
        $result_value = $values[$i];
        continue;
    }

    if($values[$i]<$result_value) {
        $result_index = $i;
        $result_value = $values[$i];
    }

}
print $result_index . " " . $result_value;
?>

Comments

0

You can build your own custom function:

function findIndex($input_array, $num)
{
    foreach($input_array as $k => $v)
    {
        if($v >= $num)
        {
           return $k;
        }       
    }

    return false;
}

This function will return array index (key). If you don't want index, but the value, then other functions posted here will do the job. You should clarify what exactly you want to get as your question is a little bit amiguous

Comments

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.