Rumah >pembangunan bahagian belakang >tutorial php >PHP中isset变量和直接判断变量的区别

PHP中isset变量和直接判断变量的区别

WBOY
WBOYasal
2016-08-08 09:19:471123semak imbas

在变量为空字符串和布尔值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>

虽然isset在判断变量没什么作用,但是在判断数组有无一个变量却很好用:

<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教程有兴趣的朋友有所帮助。

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn