在变量前面加个叹号什么意思_变量前面的感叹号 - 需要澄清

I've been working with PHP for quite a while now, but this was always a mystery to me, the correct use of the exclamation mark (negative sign) in front of variables.

What does !$var indicate? Is var false, empty, not set etc.?

Here are some examples that I need to learn...

Example 1:

$string = 'hello';

$hello = (!empty($string)) ? $string : '';

if (!$hello)

{

die('Variable hello is empty');

}

Is this example valid? Would the if statement really work if $string was empty?

Example 2:

$int = 5;

$count = (!empty($int)) ? $int : 0;

// Note the positive check here

if ($count)

{

die('Variable count was not empty');

}

Would this example be valid?

I never use any of the above examples, I limit these if ($var) to variables that have boolean values only. I just need to know if these examples are valid so I can broaden the use of the if ($var) statements. They look really clean.

Thanks.

解决方案

if(! $a) is the same as if($a == false). Also, one should take into account that type conversion takes place when using == operator.

For more details, have a look into "Loose comparisons with ==" section here. From there it follows, that for strings "0" and "" are equal to FALSE ( "0"==false is TRUE and ""==false is TRUE, too).

Regarding posted examples:

Example 1

It will work, but you should note, that both "0" and "" are 'empty' strings.

Example 2

It will work

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值