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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7908163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:36:49  来源:igfitidea点击:

Check if Variable exists and === true

phpif-statementnotice

提问by Sebastian Sebald

I want to check if:

我想检查是否:

  • a field in the array isset
  • the field === true
  • 数组 isset 中的一个字段
  • 该字段 === 真

Is it possible to check this with one ifstatement?

是否可以用一个if语句来检查这一点?

Checking if ===would do the trick but a PHP notice is thrown. Do I really have to check if the field is set and then if it is true?

检查是否===可以解决问题,但会抛出 PHP 通知。我是否真的必须检查该字段是否已设置,然后是否为真?

回答by Madara's Ghost

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).

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

Or you could suppress it with the evil @character:

或者你可以用邪恶的@角色压制它:

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

This solution is NOT RECOMMENDED

不推荐使用此解决方案

回答by askome

I think this should do the trick ...

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

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

回答by Phill Pafford

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