reitermarkus
reitermarkus

Reputation: 708

Why check if( isset($something) && $something )?

I just saw something like the following in a php file and I'm wondering why you would check both.

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

// Code

}

Does this make sense?

Upvotes: 0

Views: 6973

Answers (3)

Michael
Michael

Reputation: 920

isset will return true if the variable is defined, while the default boolean test will return true if the variable isn't empty or zero. You want to use isset before you test its value to prevent undefined variable errors.

if ($var) // returns true if the variable isn't empty or zero

if (isset($var)) // returns true if the variable is defined and not NULL

If the php error reporting level includes notices (E_NOTICE), testing undefined variables would report a undefined variable error.

However, you don't need to use isset before the function empty.

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

Upvotes: 3

Robbie
Robbie

Reputation: 17710

It's good practice to code in php with "notices" reporting as an error. If you check for the value of a variable, but that variable is not set, then it may mean that you have a typo and it will be flagged as an "error". You can then fix your typo and move on. If you didn't have notices, then you may never spot the typo and the variable will be the same as if empty/null/false (depending on your comparison) so you probably never get your "true" condition.so turn on notices and save yourself hours of debugging.

But sometimes there may be times when you know that a variable may not be set - to avoid it being reported as an error, you check the variable is "set" first. This is what you are reading in your code sample.

Upvotes: 1

Rikesh
Rikesh

Reputation: 26431

isset - Will return TRUE if it exists and is not NULL otherwise it is FALSE.

In above eg. for $var = 0

First condition of isset will return true while second condition will return false.

So the above condition will be used in case you want to check if the variable is set & have the non-zero value.

Upvotes: 3

Related Questions