Check if Variable exists and === true

前端 未结 4 1057
谎友^
谎友^ 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:18

    Alternative, just for fun

    echo isItSetAndTrue('foo', array('foo' => true))."
    \n"; echo isItSetAndTrue('foo', array('foo' => 'hello'))."
    \n"; echo isItSetAndTrue('foo', array('bar' => true))."
    \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 
    \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
    

提交回复
热议问题