Skip to content

Instantly share code, notes, and snippets.

@devudit
Last active January 6, 2024 18:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devudit/6e5a8c4cad33c73ccf2691db7717d582 to your computer and use it in GitHub Desktop.
Save devudit/6e5a8c4cad33c73ccf2691db7717d582 to your computer and use it in GitHub Desktop.
Get closest, lower and higher number as a associative array from a array
<?php
function closestLowerHigherNr($array, $nr) {
sort($array);
$re_arr = array('lower'=>min(current($array), $nr), 'higher'=>max(end($array), $nr), 'closest'=>$nr);
foreach($array AS $num){
if($nr > $num) $re_arr['lower'] = $num;
else if($nr <= $num){
$re_arr['higher'] = $num;
break;
}
}
$re_arr['closest'] = (abs($nr - $re_arr['lower']) < abs($re_arr['higher'] - $nr)) ? $re_arr['lower'] : $re_arr['higher'];
return $re_arr;
}
print_r(closestLowerHigherNr($array,180));
// The above function will return a associative array as
/*
Array (
[lower] => 150
[higher] => 200
[closest] => 200
)
*/
@KnightChaser
Copy link

thank you for your gist! It's helpful :)

@mecxi
Copy link

mecxi commented May 19, 2023

Thanks very much. That's what I was looking for. :-)

@mahmoudabdelhalim
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment