Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Check whether an integer is in a certain interval or not

I am currently working on an achievement system for a small online game. The achievement entity basically has 4 attributes:

  • id
  • earnedBy
  • earnedOn
  • progress

The last one is supposed to be a percentage, meaning a number between 0 and 100. In order to make sure that no numbers greater than 100 or smaller than 0 are saved in the database, my setter-method looks as followed (I am using Symfony2 / Doctrine ORM):

public function setProgress($progress)
    {
        $this->progress = max(min($progress, 100), 0);

        return $this;
    }

The important line here is max(min($progress, 100), 0).

It works totally fine, I just wanted to ask, if there is another built-in function in PHP doing exactly that thing, and if what I am doing is okay (concerning good-developing style)

like image 622
MrR Avatar asked Apr 01 '13 10:04

MrR


People also ask

How can check integer value or not 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 a number is a whole number in PHP?

A test then would be: if (y % 1 == 0) { // this is a whole number } else { // this is not a whole number } var isWhole = (y % 1 == 0? true: false); // to get a boolean return.


1 Answers

Since PHP 5.2 there are filter_var() functions with considerable set of options available.

One of them lets you check for number being in a range:

$param = 10;

$result = filter_var( $param, FILTER_VALIDATE_INT, [
    'options' => [
        'min_range' => 20, 
        'max_range' => 40
    ]
]);

var_dump( $result ); // will return FALSE for 10

http://codepad.viper-7.com/kVwx7L

like image 184
tereško Avatar answered Sep 23 '22 15:09

tereško