douhuanglou1445
2014-11-13 11:18
浏览 88
已采纳

filter_var boolean返回false

This is weird

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

bool(true)
bool(false)

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);

图片转代码服务由CSDN问答提供 功能建议

这很奇怪

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

我在这里缺少什么? 他们当然应该是真的吗? 如果不能如何验证错误的布尔值?

编辑:澄清。 我需要验证一个错误的布尔值。 确保它不是字符串,int,float或其他任何东西。 e.g。

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

也许我错误地提出了我的问题,或者我已经进化了太多广告,我应该问另一个问题。 < 我找到的解决方案是:

  $ result = filter_var($ bool,FILTER_VALIDATE_BOOLEAN)&amp;&amp;  ($ bool === true || $ bool === false); 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • 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));
    var_dump(filter_var(2, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));
    

    See it working

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

    打赏 评论

相关推荐 更多相似问题