Check if Variable exists and === true

烂漫一生 提交于 2019-11-28 01:49:20

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

I think this should do the trick ...

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!