How to validate an integer within a range in PHP

Problem statement: Given an integer, check if that integer is within the given range.

Example 1

  • Input: num=5, range=[3,10]
  • Output: true

Example 2

  • Input: num=12, range=[3,10]
  • Output: false

The filter_var() function

The filter_var() function in PHP is used to validate/filter a variable according to the specified filter.

Syntax

filter_var(var, filtername, options)

Parameters

  • var: The variable to be evaluated.
  • filtername: The name of the filter to use. This is an optional parameter.
  • options: Flags/options to use. This is an optional parameter.

Return value

The method returns the filtered data on successful. Otherwise, it returns false on failure.

The FILTER_VALIDATE_INT filter

The FILTER_VALIDATE_INT filter is used to check if the value is an integer. The filter optionally accepts a range when specified checks if the given integer value is within the range.

The options to specify for range check are as follows:

  • min_range: This specifies the minimum value in the integer range.
  • max_range: This specifies the maximum value in the integer range.

By combining filter_var() and FILTER_VALIDATE_INT, we can check if the given number is within the given range.

Example

<?php
$range = array('min_range' => 3, 'max_range' => 10,);
$options = array('options' => $range);
$num = 7;
if (filter_var($num, FILTER_VALIDATE_INT, $options) == false){
echo $num." is not in range ";
print_r($range);
} else{
echo $num." is in range ";
print_r($range);
}
?>

Explanation

  • Line 3: We define the range as an array.
  • Line 5: We construct the options parameter using the range array from line 3.
  • Line 7: We define the number that we have to validate.
  • Lines 9–15: We validate the number within the range using the filter_var() function and the FILTER_VALIDATE_INT filter. Depending on the result, we print a string.
Copyright ©2024 Educative, Inc. All rights reserved