直接上测试代码:
$test = ['yes'=>'ok','no'=>0,'no2'=>' ','no3'=>''];
$yes = $test['yes'] ?? 'yes'; //ok
var_dump($yes);
echo '<br>';
$yes2 = $test['yes'] ?: 'yes'; //ok
var_dump($yes2);
echo '<br>';
$no = $test['no'] ?? 'no'; //result: 0 isset
var_dump($no);
echo '<br>';
$no2 = $test['no'] ?: 'no'; //result: no !empty, but for array,if index not set, error occurs
var_dump($no2);
echo '<br>';
$no3 = $test['no2'] ?: 'no'; //result: 2 !empty
var_dump($no3);
echo '<br>';
$un = $test['un'] ?? 'un'; //result: 2
$un = $test['un'] ?: 'un'; //Notice Error
if($test['hello']) //Notice Error
{
echo 'hello';
}
if(empty($test['hello'])) //empty
{
echo 'hello is empty';
echo '<br>';
}
if(empty($test['no2'])) //not empty
{
echo 'no2 is empty';
echo '<br>';
}
if(empty($test['no3'])) //empty
{
echo 'no3 is empty';
echo '<br>';
}
$a=0;
$c=null;
$b=$a ?? 3;
$d=$c?:4;
echo '<br>';
var_dump($b);
echo '<br>';
var_dump($d);
结果:
string(2) "ok"
string(2) "ok"
int(0)
string(2) "no"
string(4) " "
Notice: Undefined index: un in D:\webroot\test\test_index.php on line 23
Notice: Undefined index: hello in D:\webroot\test\test_index.php on line 25
hello is empty
no3 is empty
int(0)
int(4)
结论:
?? 其实就是 isset($var) 的简写形式
?: 大致和!empty作用一样,但是如果是判断数组中的index,如果该index不存在,是要报Notice错误的,这点和empty函数的行为不一样,要注意
本文深入探讨了PHP中处理变量空值的两种运算符??和?:的使用方法及区别。通过具体代码示例,解析了它们在isset和empty函数上的行为差异,特别注意在数组元素检查时可能引发的Notice错误。
2488

被折叠的 条评论
为什么被折叠?



