开发者

Php filter_var function

I know that the function filter_var() returns true or false but when I mean if I have

if( filter_var( $value , FILTER_VALI开发者_JS百科DATE_INT ) )
    echo 'value is sanitized';
else 
    echo 'value is sanitized';

Can anyone explain when this function returns true or false?


It will never return true. It will return false if $value is not an integer.


As @deceze says, you either get the sanitized variable back, or FALSE if the function errors out.

Now, PHP lets you do something interesting: if a variable is defined and is used in a conditional statement, anything that could not be implicitly cast to a Boolean value of FALSE (i.e. an empty string or an actual false value) will be considered equivalent to a Boolean value of TRUE. We use this sort of thing all the time when, say, iterating over a dataset retrieved from a database.

So, if you call filter_var and successfully get a value back for $value, the if() statement surrounding the call to filter_var uses the value of $value as it's conditional.

HTH.


The return value of filter_var() is the value of the first argument if the function succeeds, otherwise it will return false.

$x = 5;
$y = 3;
$z = 11;
$t = 'abc';
$options = array(
    'options'   =>  ['min_range' => 5, 'max_range' => 10],
    'flags'     =>  FILTER_REQUIRE_SCALAR
);
if (false === filter_var($x, FILTER_VALIDATE_INT, $options)) {
    // filter_var will return the value of $x (5)
    // No exceptions will be thrown
    throw new \InvalidArgumentException("$x is not a valid input");
}
if (false === filter_var($y, FILTER_VALIDATE_INT, $options)) {
    throw new \InvalidArgumentException("$y is not a valid input");
}
if (false === filter_var($z, FILTER_VALIDATE_INT, $options)) {
    throw new \InvalidArgumentException("$z is not a valid input");
}
if (false === filter_var($t, FILTER_VALIDATE_INT, $options)) {
    throw new \InvalidArgumentException("$t is not a valid input");
}

The only variable that will not throw an exception is $x because it's an integer and it's inside the range defined by $options['options'].

See also:

  • http://php.net/manual/en/filter.filters.validate.php
  • http://php.net/manual/en/filter.constants.php
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜