變數為空
以下的東西被認為是空的:
語
- 「」 (空字串)
- 0 (作為整數的0)
- 0.0 (作為浮點數的0)」
- 0.0 」 (作為字串的0)
- NULL
- FALSE
- array() (一個空數組)
- $var; (一個聲明了,但是沒有值的變數)
語句中空值傳回,以下代碼不會產生任何輸出,因為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>
==
比較, 03:” ,都回傳trueefleled , isset, isnullempty:檢查一個變數是否為空
<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></code>
<code><?php <span>$emptyList</span> = [<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>
注意==
比較不一定回傳true :<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>
最佳實踐
空值判斷使用empty n;
').addClass('pre-numbering').hide();
$(this).addClass('has-numbering').parent().append($numbering);
for (i = 1; i ').text(i));
};
$numbering.fadeIn(1700);
});
});