php7 中 ?? 和 ?:的区别

直接上测试代码:

$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函数的行为不一样,要注意

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值