PHP if null echo else echo
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17083675/
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
PHP if null echo else echo
提问by Damian Smith
Not sure what im doing wrong here, but the out come is always null. The script should output "you did not select an answer" only if no answer was selected but otherwise it should output the answer given:
不确定我在这里做错了什么,但结果总是空的。只有当没有选择答案时,脚本才应该输出“你没有选择答案”,否则它应该输出给出的答案:
I have updated the script as mentioned but still getting the empty output even when answer is given :/
我已经更新了脚本,但即使给出了答案,仍然得到空输出:/
Thanks for all the help so far guys, but even the below code doesnt work, it now just outputs as blank if no anwser, but if you do fill it in, it correctly echos the answer.
感谢到目前为止提供的所有帮助,但即使下面的代码也不起作用,如果没有 anwser,它现在只会输出为空白,但是如果您填写它,它会正确地回应答案。
if (empty( $a1 )) {
echo"<li>\n<h2>1. " . $q1[0] . "</h2>\n"
. "<p>You did not select an answer</p>\n"
. "</li>\n";
}
else {
echo"<li>\n<h2>1. " . $q1[0] . "</h2>\n"
. "<p><strong>" . $q1[$a1] . ":</strong></p>\n"
. "<p>" . $r1[$a1] . "</p>\n"
. "</li>\n";
}
Completely forgot to show this part!!
完全忘记展示这部分!!
// get local copies of single answers
$a1 = trim(isset($_POST['a1'])?$_POST['a1']:99);
$a3 = trim(isset($_POST['a3'])?$_POST['a3']:99);
$a4 = trim(isset($_POST['a4'])?$_POST['a4']:99);
$a5 = trim(isset($_POST['a5'])?$_POST['a5']:99);
回答by Christian Mark
Don't use if($a1 == null)
use if(empty($a1))
or if(isset($a1))
不要使用if($a1 == null)
使用if(empty($a1))
或if(isset($a1))
回答by Hanky Panky
An empty string is not null
空字符串不是 null
$a1 = '';
if ($a1 == null) // is wrong
should be
应该
$a1 = '';
if ($a1 === '')
or
或者
if (empty($a1))
回答by herrhansen
an empty is not the same as null try
空与空尝试不同
if ($a === '')
this respects also the type which is better for code quality
if ($a === '')
这也尊重代码质量更好的类型
回答by som
if (empty( $a1 )) {
echo"<li>\n<h2>1. " . $q1[0] . "</h2>\n"
. "<p>You did not select an answer</p>\n"
. "</li>\n";
}
else {
echo"<li>\n<h2>1. " . $q1[0] . "</h2>\n"
. "<p><strong>" . $q1[$a1] . ":</strong></p>\n"
. "<p>" . $r1[$a1] . "</p>\n"
. "</li>\n";
}
Use empty
instead of null
checking
使用empty
而不是null
检查
回答by Snehal Chavan
'null' is not same as false or ''.'null' is an object.
'null' 不同于 false 或 ''.'null' 是一个对象。
回答by xqterry
In PHP, empty string ($a) & empty array ($b) will return true if you test following express:
在 PHP 中,如果您测试以下 express,空字符串 ($a) 和空数组 ($b) 将返回 true:
$a = ''; $b = array();
$a == null -> TRUE $b == null -> TRUE
also,
$a == 0 -> TRUE
$a = ''; $b = 数组();
$a == null -> TRUE $b == null -> TRUE
还,
$a == 0 -> TRUE
So you should use '===' to test, or there's always unexpected result in your code.
所以你应该使用 '===' 来测试,否则你的代码总是会有意想不到的结果。