PHP Useful functions (Part 1) - The inRange function

Developing websites, social applications, and scripts in PHP for more than 6 years now, I found a number of utility functions helpful in development. I am going to write a series of tutorials writing such functions and describing their use. Using these functions I have created a library of dynamically loadable classes but you are free to use them as you wish.

The inRange Function:

I am going to discuss the inRange function here. Here is the function header:

function inRange($low, $high, $val)

As can be seen the function takes three arguments a low value, high value, and the value to be compared, as input.

Examples:

I mostly use this function when I do string length verification for user input through forms and input validation. For example, you have a select box with countries with IDs from 1 to 172, you can use the function in an IF block as follows:

if(inRange(1, 172, $input)) { // do something }

You can also check the string length. For example, name field in the database allows up to 30 characters, hence you'll use the following If condition to verify the length of name input by the user.

if(inRange(1, 30, strlen($input))) { // do something }

which is obviously clearer than,

if(1 <= strlen($input) && 30 >= strlen($input)) { // do something }

OR

$len = strlen($input) if(1 <= $len && 30 >= $len) { // do something }

Function Definition:

Now, here is the definition of the function,

function isInRange($low, $high, $val) { return $val >= $low && $val <= $high; }

Did this tutorial help a little? How about buy me a cup of coffee?

Buy me a coffee at ko-fi.com

Please feel free to use the comments form below if you have any questions or need more explanation on anything. I recommend thoroughy testing on a production-like test system first before moving to production.