PHP: 4 Ways to Check if a Number is in a Range

Updated: January 9, 2024 By: Guest Contributor Post a comment

Using Comparison Operators

The fundamental way to determine if a number falls within a specified range is by using comparison operators. You simply check if the number is greater than or equal to the lower bound and less than or equal to the upper bound.

Steps:

  1. Define your range with two variables, one for the lower bound and one for the upper bound.
  2. Use the comparison operators to check if the number is between these two bounds.
  3. Return or print the result.

Example:

$lowerBound = 10;
$upperBound = 20;
$number = 15;

$result = ($number >= $lowerBound) && ($number <= $upperBound);

echo $result ? 'In range' : 'Out of range';

Notes: This method is straightforward and has excellent performance as it uses basic operations. However, be aware of edge cases such as non-numeric values and ensure input validation where necessary.

Using a Custom Function

Creating a custom function is a reusable and clean way to check a number’s range. The function encapsulates the validation logic and can be used throughout your application.

Steps:

  1. Create a function that accepts three parameters: the number, the lower bound, and the upper bound.
  2. Use comparison operators within the function to determine range.
  3. Return a boolean indicating if the number is in range.
  4. Call the function with the desired parameters.

Example:

function isNumberInRange($number, $lowerBound, $upperBound) {
    return ($number >= $lowerBound) && ($number <= $upperBound);
}

$number = 15;
if (isNumberInRange($number, 10, 20)) {
    echo 'In range';
} else {
    echo 'Out of range';
}

Notes: Using a function promotes code reuse and readability. However, the performance impact is negligible as the overhead of calling a function in PHP is minimal.

Utilizing the Range Function

PHP’s built-in range function creates an array containing a range of elements. This method checks if the number is in the generated array.

Steps:

  1. Create an array with numbers within the desired range using PHP’s range function.
  2. Use the in_array function to check if the number is in that array.
  3. Return or print the result.

Example:

$number = 15;
$range = range(10, 20);

$result = in_array($number, $range);

echo $result ? 'In range' : 'Out of range';

Notes: This method is not recommended for large ranges as it will consume more memory and processing time. range generates a potentially large array which may be inefficient for simple range checking.

Interval Comparison with the Ternary Operator

This concise approach uses the ternary operator to perform an in-line comparison, making your code shorter and sometimes more readable.

Steps:

  1. Define the upper and lower bounds of your range.
  2. Use the ternary operator to perform the range check and return a message in one line of code.

Example:

$lowerBound = 10;
$upperBound = 20;
$number = 15;

echo ($number >= $lowerBound && $number <= $upperBound) ? 'In range' : 'Out of range';

Notes: While the ternary operator can make code more concise, it may also reduce readability, especially for complex conditions. Use with caution and always aim for clarity over brevity.

Final Words

Checking if a number falls within a specific range is a common programming task in PHP, and there are several methods to accomplish this. From simple comparison operators to custom functions and built-in PHP functionalities, choosing the best approach depends on factors like performance, memory usage, readability, and code maintainability.

For most use cases, basic comparison operators are sufficient and offer the best performance. However, encapsulating this logic within a function can significantly increase code readability and reusability without any significant performance cost. Avoid using the range function with in_array for checking number ranges unless dealing with small sets of data, as it can be inefficient for larger ranges. The ternary operator provides a compact syntax, but developers should prioritize code clarity to ensure long-term maintainability.

In conclusion, PHP provides multiple ways to determine number ranges, with various trade-offs. Assess the context in which range checking is needed and choose the approach that best aligns with your application’s performance and code quality requirements.