为什么这个 IF 语句会让我的 php 崩溃


Why is this IF statement crashing my php?

在我的php文件中,我有这样的语句:

if($_POST['married'] === true) $married = 'yup' else $married = 'nop';

但是如果我不评论它,我的 php 结果页面就会变成空。它几乎崩溃了。我正在从不同的地方发布到这个 PHP,并且在 POST 值中我有"已婚"值。它确实是空的(不是真的或假的),但这与它无关。我也试过这种方式:

if($_POST['married'] === '') $married = 'yup' else $married = 'nop';

相同的结果。空白页。我的语法有问题吗?我看不到我的问题。请帮助我。

您没有正确使用if

if($_POST['married'] == true)
{
    $married = 'yup';
}
else
{
    $married = 'nop';
}

===也不能用于 POST,因为它会自动将所有内容作为字符串发布;===比较器比较数据类型和内容。

号哥们!!

if($_POST['married'] === '')  $married = 'yup'; else $married = 'nop';

你忘了把分号放在"yup"后面。它会是

 if($_POST['married'] === true) $married = 'yup'; else $married = 'nop';

或者,如果您希望使用 OneLiner,则:

 ($_POST['married']===true)?($married = 'yup'):($married = 'nop');

您需要在每个语句后添加一个分号:

if($_POST['married'])
    $married = 'yup';
else
    $married = 'nop';

您可能还想检查它是否首先使用 isset 设置:

if(isset($_POST['married']) && $_POST['married'] === true)
    $married = 'yup';
else
    $married = 'nop';

http://php.net/manual/en/function.isset.php

您也可以使用 tenary 编写语句:

$married = isset($_POST['married']) && $_POST['married'] === true ? 'yup' : 'nop';

有关租赁运营商的更多信息:http://www.sitepoint.com/using-the-ternary-operator/

$married = 'yup' 后添加一个分号,并使用 isset 来确定是否设置了$_POST值:

if(isset($_POST['married']) && $_POST['married'] == true)
    $married = 'yup';
else
    $married = 'nop';

您错过了 if 语句中的分号,并尝试检查是否设置了 $_POST 变量

if(isset($_POST['married']) === true) 
  $married = 'yup';//Here you missed the semicolon
else 
  $married = 'nop';

空运算符将帮助您:

if(!empty($_POST['married'])) {
  $married = 'yup';
}
else {
  $married = 'nop';
}

我假设show_errors = false所以它在无声地轰炸?如果是这样(在开发期间),请确保打开错误报告。

话虽如此,您应该始终在使用它们之前检查$_POST/$_GET值。

例如
$married = isset($_POST['married']) && ((bool)$_POST['married'])
         ? 'yup'
         : 'nop';

您的页面崩溃,因为缺少分号。

if()不需要分号,因为它是子句而不是语句。 $married = 'yup'是需要分号 (;) 的语句终止。