2014-11-13 11:18 阅读 68

filter_var boolean返回false

This is weird

var_dump(filter_var(true, FILTER_VALIDATE_BOOLEAN));
var_dump(filter_var(false, FILTER_VALIDATE_BOOLEAN));


What an I missing here? Surely they should both be true? If not how can I validate a false boolean?

Edit: To clarify. I need to validate a false boolean. To ensure it's not a string, int, float or anything else. e.g.

$var = false; //true
$var = true; //true
$var = 'foo'; //false
$var = 1; //false

Perhaps I asked my question incorrectly or I've evolved it too much ad I should ask another question.

Solution I went for was:

$result = filter_var($bool, FILTER_VALIDATE_BOOLEAN) && ($bool===true||$bool===false);
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongli2000 dongli2000 2014-11-13 11:22

    From the manual:-

    If FILTER_NULL_ON_FAILURE is set, FALSE is returned only for "0", "false", "off", "no", and "", and NULL is returned for all non-boolean values.

    Set this and if null is returned, you don't have a bool (or boolish) value.

    For example:-

    var_dump(filter_var(true, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));
    var_dump(filter_var(false, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));

    See it working

    However, it may be that is_bool() is more appropriate here.

    点赞 评论 复制链接分享