php if, and, or : 要检查的多个变量。工作,但得到变量未定义的错误

php if, and, or : multiple variables to check. Working, but getting variable not defined errors

基本上,我正在尝试检查是否存在任何变量,如果存在,则 运行 片段,无论其他变量是否存在。

我正在使用:

if ($a1 || $a2 || $a3 || $a4):
$a = "success";
endif;

如果只有 $a4 存在,这将起作用并设置 $a 变量。但是,我在 $a4.

之前收到任何变量未定义错误

如果 $a0 变量不存在 (NULL),则设置不同的变量:

if (!empty($a0) && $a1 || $a2 || $a3 || $a4) :
$a-alt = "no0success";
endif;

此代码运行良好。但是,它给了我变量未定义的错误。

利用isset函数,试试这样的

if( isset($variable) ){
   // do so and so....
}else
{
   // define variable
   $variable = 'foo';
} 

您可以检查是否设置了每个变量。 PHP的短路逻辑将确保您不会出现任何错误:

if ((isset($a1) && $a1) ||
    (isset($a2) && $a2) ||
    (isset($a3) && $a3) ||
    (isset($a4) && $a4)) 
    $a = "success";
endif;

请注意,由于 && 的优先级高于 ||,因此额外的大括号是多余的,但恕我直言,它们增加了代码段的可读性。