PHP considers null is equal to zero

2019-01-18 08:22发布

In php, ($myvariable==0) When $myvariable is zero, the value of the expression is true; when $myvariable is null, the value of this expression is also true. How can I exclude the second case? I mean I want the expression to be true only when $myvariable is zero. Of course I can write

($myvariable!=null && $myvariable==0 )

but is there other elegant way to do this?

标签: php null
11条回答
霸刀☆藐视天下
2楼-- · 2019-01-18 09:00

If your zero could be a string, you should also considere checking the "zero string"

($myvariable === 0 || $myvariable === '0')
查看更多
Bombasti
3楼-- · 2019-01-18 09:00

I hade faced a similar issue in one of my projects, with a minor difference that I was also using the values ZERO as a valid value for my condition. here's how I solved it using simple logic to separate NULL from zero and other values.

    if (gettype($company_id) === 'NULL') {
        $company = Company::where('id', Auth::user()->company_id)->first();
    } else {
        $company = Company::where('id', $company_id)->first();
    }
查看更多
一纸荒年 Trace。
4楼-- · 2019-01-18 09:01
$myvariable === 0

read more about comparison operators.

查看更多
劳资没心,怎么记你
5楼-- · 2019-01-18 09:01

There's an is_null function, but this will just replace your $myvariable!=null

查看更多
来,给爷笑一个
6楼-- · 2019-01-18 09:04

Try ($myvariable === 0) which will not perform type coercion.

查看更多
登录 后发表回答