Last active
January 6, 2024 18:22
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
) | |
*/ |
Thanks very much. That's what I was looking for. :-)
Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you for your gist! It's helpful :)