Jump to content

Recommended Posts

I wish to return the object in an array with the highest index where its index falls between between integers, and return null should one not exist.

For instance, with the following and a min and max of 10,000 and 15,000, it should return OBJ4, and with a min and max of 15,000 and 20,000 it should return NULL.

Any thoughts?  Thanks

function getObj(int $min, int $max):?OBJ {
    $list=[
        12314=>'OBJ1',
        321=>'OBJ2',
        42142=>'OBJ3',
        14314=>'OBJ4',
        123=>'OBJ5',
        13314=>'OBJ6'
    ];
    return getIt($list, $min, $max);
}

 

One way ...

$list=[
        12314=>'OBJ1',
        321=>'OBJ2',
        42142=>'OBJ3',
        14314=>'OBJ4',
        123=>'OBJ5',
        13314=>'OBJ6'
    ];

function getIt($list, $min, $max)
{
    $arr = array_filter($list, function ($k) use ($min,$max) {
                                   return $k >= $min && $k <= $max;
                                }, ARRAY_FILTER_USE_KEY);
    krsort($arr);
    return current($arr);
}

echo getIt($list, 10000, 15000);          // OBJ4
echo getIt($list, 15000, 20000);          // false

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.