I am currently working on an achievement system for a small online game. The achievement entity basically has 4 attributes:
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)
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With