Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using filter_var with parameters

Tags:

php

I am trying check if variable is integer number and if she is in diapason: 2-15.

I am trying make this using filter_var() function. but I dont understood how correct use min_range and max_range parameters.

this not works, where I am wrong?

$c = 48;

if ( filter_var($c, FILTER_VALIDATE_INT , array("min_range"=>2,"max_range"=>15)) === false ) {
    echo "bad";
}
like image 747
Oto Shavadze Avatar asked Jan 30 '13 13:01

Oto Shavadze


People also ask

What should the Filter_var () function be used on?

filter_var() is a PHP function used to filters a variable with the help of a specified filter. In PHP programming language we can use filter_var() function to validate and sanitize a data such as email id, IP address etc.

What is the use of the Filter_var () and Filter_input () functions in PHP?

filter_var. If a variable doesn't exist, the filter_input() function returns null while the filter_var() function returns an empty string and issues a notice of an undefined index.

What is filter var return?

Return Value: It returns the filtered data on success, or FALSE on failure. $str = "<h1>GeeksforGeeks! </h1>" ; $newstr = filter_var( $str , FILTER_SANITIZE_STRING);


2 Answers

The min_range and max_range values have to be one level, deeper:

// for filters that accept options, use this format
$options = array(
    'options' => array(
        'default' => 3, // value to return if the filter fails
        // other options here
        'min_range' => 0
    ),
    'flags' => FILTER_FLAG_ALLOW_OCTAL,
);

See: http://php.net/filter_var

So:

$c = 48;

if (filter_var($c, FILTER_VALIDATE_INT, array("options" => array("min_range"=>2,"max_range"=>15))) === false) {
    echo "bad";
}
like image 120
Tobias Avatar answered Oct 04 '22 18:10

Tobias


They should be in the options array:

if ( filter_var($c, FILTER_VALIDATE_INT, array(
        "options"=>array(
            "min_range"=>2,
            "max_range"=>15
        )
    )) === false ) {
    echo "bad";
}

Seems overly complicated way to write 2 <= $c && $c <= 15 though

like image 20
Esailija Avatar answered Oct 04 '22 16:10

Esailija