Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an integer is within a range of numbers in PHP?

Tags:

php

int

range

How can I check if a given number is within a range of numbers?

like image 973
Richard Peers Avatar asked Jan 13 '11 18:01

Richard Peers


People also ask

How do you check if a number is within a range?

If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range.

How do you check if a value is an integer in PHP?

The is_int() function checks whether a variable is of type integer or not. This function returns true (1) if the variable is of type integer, otherwise it returns false.

How do you check if an integer is a number?

The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .


2 Answers

The expression:

 ($min <= $value) && ($value <= $max) 

will be true if $value is between $min and $max, inclusively

See the PHP docs for more on comparison operators

like image 92
Dancrumb Avatar answered Oct 14 '22 11:10

Dancrumb


You can use filter_var

filter_var(     $yourInteger,      FILTER_VALIDATE_INT,      array(         'options' => array(             'min_range' => $min,              'max_range' => $max         )     ) ); 

This will also allow you to specify whether you want to allow octal and hex notation of integers. Note that the function is type-safe. 5.5 is not an integer but a float and will not validate.

Detailed tutorial about filtering data with PHP:

  • https://phpro.org/tutorials/Filtering-Data-with-PHP.html
like image 30
Gordon Avatar answered Oct 14 '22 09:10

Gordon