NotionCommotion Posted December 17, 2019 Share Posted December 17, 2019 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); } Quote Link to comment https://forums.phpfreaks.com/topic/309699-selecting-array-elements-based-on-an-index-range/ Share on other sites More sharing options...
Barand Posted December 17, 2019 Share Posted December 17, 2019 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 Quote Link to comment https://forums.phpfreaks.com/topic/309699-selecting-array-elements-based-on-an-index-range/#findComment-1572589 Share on other sites More sharing options...
NotionCommotion Posted December 18, 2019 Author Share Posted December 18, 2019 Thanks Barand Quote Link to comment https://forums.phpfreaks.com/topic/309699-selecting-array-elements-based-on-an-index-range/#findComment-1572602 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.