这里的重复没有任何问题。在检查变量是否已设置之前,不能将 $inputs['user_id'] 分配给变量,否则会产生 Notice undefined index ...。
这里唯一可以做的就是省略isset 调用并改用!empty,如下所示:
if(!empty($inputs['user_id'])) {
doSomething($inputs['user_id']);
}
现在您只需输入两次并检查
!empty($inputs['user_id'])
等于
isset($inputs['user_id']) && $inputs['user_id']
编辑: 基于一个 cmets,这里引用 documentation:
以下的东西被认为是空的:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
所以empty(0) 或empty('0') 将返回true,这意味着
if(!empty('0') || !empty(0)) { echo "SCREW YOU!"; }
什么都不回应...或者,以礼貌的方式,我将重复上面的陈述:
!empty($inputs['user_id']) === (isset($inputs['user_id']) && $inputs['user_id'])
编辑 2:
通过省略isset 并用!empty 替换变量仍然检查,索引是否已设置,请阅读documentation,其中说:
如果变量不存在,则不会生成警告。这意味着 empty() 本质上是与 !isset($var) || 的简明等效。 $var == false.