Check if Variable exists and === true

前端 未结 4 1053
谎友^
谎友^ 2020-12-07 00:52

I want to check if:

  • a field in the array isset
  • the field === true

Is it possible to check this with one if statement?

相关标签:
4条回答
  • 2020-12-07 01:05

    If you want it in a single statement:

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

    If you want it in a single condition:

    Well, you could ignore the notice (aka remove it from display using the error_reporting() function).

    Or you could suppress it with the evil @ character:

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

    This solution is NOT RECOMMENDED

    0 讨论(0)
  • 2020-12-07 01:18

    Alternative, just for fun

    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';
    }
    

    results:

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

    Alternative Syntax as well:

    $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;
    }
    

    Results:

    Array index: foo is set and has a true value
    
    0 讨论(0)
  • 2020-12-07 01:20

    I think this should do the trick ...

    if( !empty( $arr['field'] ) && $arr['field'] === true ){ 
        do_something(); 
    }
    
    0 讨论(0)
  • 2020-12-07 01:30

    You can simply use !empty:

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

    This is precisely equivalent to your conditions by DeMorgan's law. From PHP's documentation, empty is true iff a variable is not set or equivalent to FALSE:

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

    As you can see, all three of these statements are logically equivalent.

    0 讨论(0)
提交回复
热议问题