Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between if(!$variable) and if(isset($variable))?

Tags:

php

What is the difference between if(!$variable) and if(isset($variable))?

like image 894
Steven Hammons Avatar asked Mar 02 '11 08:03

Steven Hammons


People also ask

What does if Isset mean?

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

Is there a difference between isset and empty?

The empty() function is an inbuilt function in PHP that is used to check whether a variable is empty or not. The isset() function will generate a warning or e-notice when the variable does not exists. The empty() function will not generate any warning or e-notice when the variable does not exists.

What is the purpose of a Isset function in PHP?

The isset function in PHP is used to determine whether a variable is set or not. A variable is considered as a set variable if it has a value other than NULL. In other words, you can also say that the isset function is used to determine whether you have used a variable in your code or not before.

Does Isset check for empty string?

"isset() checks if a variable has a value including (False, 0 or empty string), but not NULL.


1 Answers

Well, the answer is pretty simple. isset($var) returns whether or not a variable exists and is not null, where !$var tells you if that variable is true, or anything that evaluates to true (such as a non-empty string). This is summarized in the first table of this documentation page.

Also, using !$var will output a notice that you're using an undefined variable, whereas isset($var) won't do that.

Mind you, they are two different things:

<?php
var_dump( isset($foo) ); // false.
var_dump( !$foo );       // true, but with a warning.

$foo = false;
var_dump( isset($foo) ); // true
var_dump( !$foo );       // true.
like image 112
Berry Langerak Avatar answered Sep 25 '22 02:09

Berry Langerak