Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP getting a value where key is between a range

Tags:

php

Is there are any efficient way to get a value. where the key is between range? for example. i want a value where the key is 13 or any range in that array that includes 13. as you can see the second element's range is 11-25. so i should get that value. because 11-25 also includes 13

$array = array(
    '0-10'   => 'a Value',
    '11-25'  => 'another Value',
    '26-50'  => 'value',
    '51-100' => 'another string'
);
like image 305
Abdullah Mallik Avatar asked Oct 21 '25 16:10

Abdullah Mallik


1 Answers

Here is what you can do:

function findInRange($number, $array)
{
    foreach ($array as $key => $value) {
        list($min, $max) = explode('-', $key);

        if ($number >= $min && $number <= $max) {
            return $value;
        }
    }

    return null;
}

$number = 13;
$array = [
    '0-10' => 'a Value',
    '11-25' => 'another Value',
    '26-50' => 'value',
    '51-100' => 'another string'
];

$result = findInRange($number, $array);

var_dump($reesult);
like image 106
xpuc7o Avatar answered Oct 23 '25 07:10

xpuc7o



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!