【问题标题】:Check if Variable exists and === true检查变量是否存在和 === true
【发布时间】:2011-12-16 00:40:39
【问题描述】:

我想检查是否:

  • 数组 isset 中的一个字段
  • 字段 === true

是否可以用一个if 语句检查这一点?

检查=== 是否可以解决问题,但会抛出 PHP 通知。我真的必须检查该字段是否已设置,然后是否为真?

【问题讨论】:

    标签: php if-statement notice


    【解决方案1】:

    我认为这应该可以解决问题...

    if( !empty( $arr['field'] ) && $arr['field'] === true ){ 
        do_something(); 
    }
    

    【讨论】:

    • 我认为关键是在一个单一的条件下......但也许这就是他的意思,我误解了。
    • 他说了一个 IF 语句,就是一个。拥有 && 不会使它成为两个,是吗?如果是这样,那我想我错了。没想到你回复的内容,聪明:)
    • 我的问题是,当我签入单个语句时,通知被抛出。但是@会做我认为的伎俩。我以为我做错了什么:-/
    • empty() 和 inset() 分别会消除该错误,至少它对我有用。然而@确实更短更甜。祝你未来的事业好运:)
    【解决方案2】:

    如果您希望在单个语句中使用它:

    if (isset($var) && ($var === true)) { ... }
    

    如果您希望它在单个条件中:

    好吧,您可以忽略该通知(也就是使用 error_reporting() 函数将其从显示中删除)。

    或者你可以用邪恶的@ 字符来压制它:

    if (@$var === true) { ... }
    

    此解决方案不推荐

    【讨论】:

    • 我认为该通知是一个错误,但如果可以取消它,我很好:) 非常感谢
    • @distractedBySquirrels 如果您认为问题正确,请不要忘记接受问题。
    • @Trurh: 抱歉 :) 带着我的手机在这里。
    • @ 运营商大多数时候都很糟糕。我不建议任何人使用它:)
    【解决方案3】:

    另类,只是为了好玩

    echo isItSetAndTrue('foo', array('foo' => true))."<br />\n";
    echo isItSetAndTrue('foo', array('foo' => 'hello'))."<br />\n";
    echo isItSetAndTrue('foo', array('bar' => true))."<br />\n";
    
    function isItSetAndTrue($field = '', $a = array()) {
        return isset($a[$field]) ? $a[$field] === true ? 'it is set and has a true value':'it is set but not true':'does not exist';
    }
    

    结果:

    it is set and has a true value
    it is set but not true
    does not exist
    

    还有替代语法:

    $field = 'foo';
    $array = array(
        'foo' => true,
        'bar' => true,
        'hello' => 'world',
    );
    
    if(isItSetAndTrue($field, $array)) {
        echo "Array index: ".$field." is set and has a true value <br />\n";
    } 
    
    function isItSetAndTrue($field = '', $a = array()) {
        return isset($a[$field]) ? $a[$field] === true ? true:false:false;
    }
    

    结果:

    Array index: foo is set and has a true value
    

    【讨论】:

      【解决方案4】:

      你可以简单地使用!empty:

      if (!empty($arr['field'])) {
         ...
      }
      

      这正好等价于德摩根定律的条件。从PHP's documentationempty 为真,如果未设置变量或等价于FALSE

        isset(x) && x
        !(!isset(x) || !x)
        !empty(x)
      

      如您所见,这三个语句在逻辑上都是等价的。

      【讨论】:

        猜你喜欢
        • 2014-09-08
        • 2016-12-28
        • 2017-11-14
        • 2013-11-13
        • 2014-06-23
        • 2017-08-05
        • 2010-10-25
        • 2017-02-13
        相关资源
        最近更新 更多