Harea Costicla
Harea Costicla

Reputation: 817

Compare 2 differents conditions with the same idea

I have a question : what is the difference between : $value !='' and !isset($value) ?

Upvotes: 0

Views: 51

Answers (3)

Hirdesh Vishwdewa
Hirdesh Vishwdewa

Reputation: 2362

isset() will tell you about the existence of the variable and is not NULL.

empty() can tell you about both, existence of the variable & the value of the variable.

Ex.

$var1  = "";
echo isset($var1);

Output:- true

So to check if the variable was set then use isset() and if you want to check if the value of variable was not a null/empty use empty().

$value != '' means you are checking if $value is not an empty string.

!isset($value) determine if a variable $value is not set and is NULL

Read these links for more information on isset & empty

What's the difference between 'isset()' and '!empty()' in PHP?

http://php.net/manual/en/function.isset.php

http://php.net/manual/en/types.comparisons.php

Upvotes: 0

Henders
Henders

Reputation: 1215

The main difference in practical use between $value != '' and !isset($value) is that you can use isset() like this:

if(!isset($value)){
    echo '$value is not declared or is equal to null';
}

If $value is not actually set then you won't get a notice with isset(). If you did something like this:

if($value != ''){
    echo $value." is not equal to nothing"; 
}

If $value is not set then this will cause a notice in PHP explaining that $value has not yet been declared.

The thing to note is that isset() will check that the variable has been declared but will not check that it isn't equal to ''.


But what about empty()?

The other part of the puzzle here would be empty() which will check whether a variable is declared and is not equal to ''. You could do something like this:

if(!empty($value)){
    echo 'We know that $value is declared and not equal to nothing.';
}

which would be the same as doing this:

if(isset($value) && $value != ''){
    echo 'We know that $value is declared and not equal to nothing.';
}

Further reading:

isset() - PHP docs

empty() - PHP docs

isset, empty checks - similar question

Why check both isset and empty?

All of these examples work in PHP 5.3+

Upvotes: 3

Buksy
Buksy

Reputation: 12218

$variable != '' simply checks variable against empty string value ( or null because '' == null), if variable is not defined notice will be shown.

!isset($variable) checks whether variable is defined and if it is not returns true, no error/notice will be shown.


But be aware that isset may return false even when variable is defined

$variable = null;
var_dump(isset($variable));  // prints false

To check if variable is truly defined within the current scope, use 'array_key_exists' with 'get_defined_vars'

$variable = null;
var_dump(array_key_exists('value', get_defined_vars()));  // prints true

Upvotes: 0

Related Questions