Heim > Artikel > Backend-Entwicklung > php 相等性比较 以及 empty,isset, isnull
变量为空
以下的东西被认为是空的:
- “” (空字符串)
- 0 (作为整数的0)
- 0.0 (作为浮点数的0)
- “0” (作为字符串的0)
- NULL
- FALSE
- array() (一个空数组)
- $var; (一个声明了,但是没有值的变量)
判断语句中空值返回false,以下代码不会产生任何输出,因为if 语句中的判断都为false:
<code><span>$emptyList</span> = [<span>""</span>, <span>0</span>, <span>0.0</span>, <span>"0"</span>, <span>NULL</span>, <span>FALSE</span>, <span>array</span>(), <span>$var</span>, ]; <span>foreach</span>(<span>$emptyList</span><span>as</span><span>$val</span>) { <span>if</span> (<span>$val</span>) { var_dump(<span>$val</span>); } }</code>
比较运算符: ==
与 ===
==
只涉及到值的比较<code>var_dump(<span>0</span> == <span>'0.0'</span>); <span>//</span><span>true</span> var_dump(<span>0</span> == <span>''</span>); <span>//</span><span>true</span> var_dump(<span>0</span> == <span>false</span>); <span>//</span><span>true</span></code>
===
同时涉及 值 与类型的比较, 更为严格<code>var_dump(<span>0</span> === <span>'0.0'</span>); <span>//</span><span>false</span> var_dump(<span>0</span> === <span>''</span>); <span>//</span><span>false</span> var_dump(<span>0</span> === <span>false</span>); <span>//</span><span>false</span></code>
==
比较, 除了 “0” ,都返回true:<code><span><span><?php </span><span>$emptyList</span> = [<span>""</span>, <span>0</span>, <span>0.0</span>, <span>"0"</span>, <span>NULL</span>, <span>FALSE</span>, <span>array</span>(), <span>$var</span>, ]; <span>foreach</span>(<span>$emptyList</span><span>as</span><span>$val</span>) { var_dump(<span>$val</span> == <span>null</span>); }</span></span></code>
empty, isset, isnull
<code><?php <span>$emptyList = [<span>""</span>, <span>0</span>, <span>0.0</span>, <span>"0"</span>, NULL, FALSE, array(), <span>$var</span>, ]; foreach (<span>$emptyList</span> as <span>$e</span>) { var_dump(empty(<span>$e</span>)); } /* bool(<span>true</span>) bool(<span>true</span>) bool(<span>true</span>) bool(<span>true</span>) bool(<span>true</span>) bool(<span>true</span>) bool(<span>true</span>) bool(<span>true</span>) */</code>
<code><span>$var</span> = <span>1</span>; var_dump(<span>isset</span>(<span>$var</span>)); <span>// true</span><span>unset</span>(<span>$var</span>); var_dump(<span>isset</span>(<span>$var</span>)); <span>// false</span><span>$var</span> = <span>null</span>; var_dump(<span>isset</span>(<span>$var</span>)); <span>// false</span></code>
=== null
。注意
空值之间的==
比较不一定返回 true :
<code><span>// 不具传递性</span><span>var_dump(<span>0</span> == <span>'0'</span>)</span>; <span>// true</span><span>var_dump(<span>''</span> == <span>0</span> )</span>; <span>// true</span><span>var_dump(<span>'0'</span> == <span>''</span>)</span>; <span>// false</span><span>var_dump(<span>0</span> == [])</span>; <span>// false</span></code>
最佳实践
==
和 ===
差别在于后者同时进行类型相等判断以上就介绍了php 相等性比较 以及 empty,isset, isnull,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。