What's the difference between is_null($var) and ($var === null)?
Is there any difference between this...
if (is_null($var)) {
do_something();
}
and this?
开发者_Go百科if ($var === null) {
do_something();
}
Which form is better when checking whether or not a variable contains null? Are there any edge cases I should be aware of? (I initialize all my variables, so nonexistent variables are not a problem.)
empty()
and isset()
do not trigger a PHP warning if their parameter is an undefined variable.
In most cases, such a warning is desirable to pinpoint the bugs. So only use the functions if you believe your variable can be legitimately undefined. It normally happens with an array index.
✅
is true
❌
is false
| isset | is_null | === null | == null | empty |
|-------|----------|---------|----------|---------|---------|
| unset | ❌ | ✅ | ✅ | ✅ | ✅ |
| null | ❌ | ✅ | ✅ | ✅ | ✅ |
| true | ✅ | ❌ | ❌ | ❌ | ❌ |
| false | ✅ | ❌ | ❌ | ✅ | ✅ |
| 0 | ✅ | ❌ | ❌ | ✅ | ✅ |
| 1 | ✅ | ❌ | ❌ | ❌ | ❌ |
| \0 | ✅ | ❌ | ❌ | ❌ | ❌ |
| "" | ✅ | ❌ | ❌ | ✅ | ✅ |
| [] | ✅ | ❌ | ❌ | ✅ | ✅ |
精彩评论