Created
August 13, 2016 19:12
-
-
Save Krzysiu/e44e0d5887889454c2b2b3d251a6dbc5 to your computer and use it in GitHub Desktop.
Check if number is within range - either open or closed one.
This file contains hidden or 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 | |
/*! Checks if numer is within range | |
* @param numeric $number number to check | |
* @param arr $range array in format [min, max, 'open' => bool] | |
* @return Boolean result | |
* @ingroup math | |
* @version 1 | |
* @note It's very simple, but I've seen a lot of examples which used range() and in_array() which is wrong wrong wrong. Also most of them support only open ranges. | |
*/ | |
function inRange($number, $range) { | |
if (!is_numeric($number)) return false; | |
$number = floatval($number); | |
$range['open'] = $range['open'] ?? true; // for PHP6 change it to: $range['open'] = isset($range['open']) ? $range['open'] : true; | |
if ($range['open'] && $number >= $range[0] && $number <= $range[1]) return true; | |
if (!$range['open'] && $number > $range[0] && $number < $range[1]) return true; | |
return false; | |
} | |
This file contains hidden or 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 | |
inRange(4, [1, 4]); // true | |
inRange(4, [1, 4, 'open' => false]); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment