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

时间:2011-10-26 19:59:20

标签: php if-statement notice

我想检查一下:

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

是否可以使用一个if声明进行检查?

检查===是否可以执行此操作,但会抛出PHP通知。我是否真的必须检查字段是否已设置,然后是否为真?

4 个答案:

答案 0 :(得分:25)

如果您想要一个语句

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

如果您想要一个条件

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

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

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

此解决方案 NOT WOMMENDED

答案 1 :(得分:2)

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

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

答案 2 :(得分:1)

另类,只是为了好玩

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

答案 3 :(得分:0)

您可以简单地使用!empty

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

这完全等同于您的德摩根法律所规定的条件。从PHP's documentation开始,如果没有设置变量或等效于empty,则FALSE为真:

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

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

相关问题