开发者

Difference between if(isset($var)) and if($var) [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Whats the difference between if(!Variable) and if(isset($variable)) ?

In Facebooks php API example they use if($var){ //do something }else{ //do something else} whick got me thinking 开发者_运维知识库about the difference of if($var) and if(isset($var)). The first sure looks neater but can I surely use it?


Using

if ($var)

You'll test if $var contains a value that's not false -- 1 is true, 123 is too, ...

For more informations about what is considered as true or false, you should take a look at Converting to Boolean.


Using isset(), you'll test if a variable has been set -- i.e. if any not-null value has been written to it.


The difference is that the isset will be true for any variable that has been declared/initalized to anything (besides null). the if($var) is true for all values of var OTHER THAN those that evaluate to false (0, '', null, false, etc).

So the difference is for values that are not null, but still evaluate to false: 0, '' (empty string), false, empty array, etc.

Try this:

$var = '';  //or equivalently 0, false, ''

if(isset($var)) echo 'a';
if($var) echo 'b';


isset will check if a variable has been set, and if ($var) will check if the variable is true.

if ($var) will throw a warning if the variable isn't set, so it's best practice to do this

if (isset($var) && $var)

Which will check if it's set AND it's true


The key difference here is between variables and values. The two items of code you refer to different concepts.

if (isset($var)) {

This tests to see if a variable has been set. The only other check it does is to see that $var is not set to null (since that is pretty much equivalent to unsetting it).

if ($var) {

This tests to see if the value that $var refers to is truthy. This may seem like an odd concept, but sometimes non-intuitive things happen in PHP with comparisions. The conditional will pass if the value of $var is anything that is true when converted to a boolean. See the manual for a list of what is converted to true and what is converted to false.

Finally

There is often a case for using both. Because isset is a language feature not a standard function, you can pass any variable name to it and it won't throw an error. It will merely return false if the variable is not defined. However, if you try using a non-initialised variable outside that context, you'll get errors reported.

That's why you'll often see code that checks to see that the value is both set and truthy:

if (isset($var) && $var) {


if($var) tests the truth value of $var, while isset($var) checks if $var has been initialized or not. If $var has not been initialized, if($var) will throw a notice "unknown variable var". But isset will check if $var is set; if $var is initialized it will return its value otherwise return false.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜