在變數為空字串和布林值false以及數值0時,isset全部回傳true,直接判斷全部回傳false:
<code><span>$empty</span>=<span>''</span>; <span>echo</span> (<span>isset</span>(<span>$empty</span>)?<span>'1'</span>:<span>0</span>);<span>//1</span><span>echo</span><span>'<br/>'</span>; <span>echo</span> (<span>$empty</span>?<span>'1'</span>:<span>0</span>);<span>//0</span></code>
<code><span>$empty</span>=<span>false</span>; <span>echo</span> (<span>isset</span>(<span>$empty</span>)?<span>'1'</span>:<span>0</span>);<span>//1</span><span>echo</span><span>'<br/>'</span>; <span>echo</span> (<span>$empty</span>?<span>'1'</span>:<span>0</span>);<span>//0</span></code>
<code><span>$empty</span>=<span>0</span>; <span>echo</span> (<span>isset</span>(<span>$empty</span>)?<span>'1'</span>:<span>0</span>);<span>//1</span><span>echo</span><span>'<br/>'</span>; <span>echo</span> (<span>$empty</span>?<span>'1'</span>:<span>0</span>);<span>//0</span></code>
只有在變數為null時,它們才是沒有差別的:
<code><span>$empty</span>=<span>null</span>; <span>echo</span> (<span>isset</span>(<span>$empty</span>)?<span>'1'</span>:<span>0</span>);<span>//0</span><span>echo</span><span>'<br/>'</span>; <span>echo</span> (<span>$empty</span>?<span>'1'</span>:<span>0</span>);<span>//0</span></code>
issetet在判斷變數沒什麼作用,但是在判斷數組有無一個變數卻很好用:
<code><span>$arr</span>=<span>array</span>(<span>'1'</span>=><span>1</span>,<span>'3'</span>=><span>3</span>); <span>$temp</span>=<span>null</span>; <span>//PS:php中数组不同于map,如果没有key而你去取值会引发错误而不是返回null,所以要有对应的判断,先判断再取值</span><span>if</span> (<span>isset</span>(<span>$arr</span>[<span>'2'</span>])) {<span>//效果等同于array_key_exists('2', $arr),但相对代码短一点</span><span>$temp</span>=<span>$arr</span>[<span>'2'</span>]; } <span>echo</span><span>$temp</span>;</code>
還有對isset不了解的可以去官網看一下就明白了:
http://php.net/manual/zh/function.isset.php
版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。
以上就介紹了PHP中isset變數和直接判斷變數的區別,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。