检查变量是否存在并且=== true


Check if Variable exists and === true

我想检查一下是否:

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

有可能用一个if语句来检查这个吗?

检查===是否会执行此操作,但会抛出PHP通知。我真的需要检查字段是否设置,然后检查它是否为真吗?

如果您想在单个语句中使用:

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

如果你想在一个单独的条件:

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

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

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

此解决方案为不推荐

我想这应该能奏效。

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

可选,只是为了好玩

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

您可以简单地使用!empty:

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

这完全等同于你的条件,根据DeMorgan定律。从PHP的文档中可以看出,如果变量没有设置或不等于FALSE,则empty为true:

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

可以看到,这三个语句在逻辑上是等价的。