Reputation: 299
What is the difference between isset($var) == "Test"
and isset($var) && $var == 'Test"
?
Upvotes: 2
Views: 174
Reputation: 6889
Here a short example:
$var = "Chuck Test";
var_dump(isset($var)); // bool(true)
var_dump(isset($undefined)); // bool(false)
var_dump(isset($var) == "Chuck Test"); // bool(true)
var_dump(isset($var) && $var == "Chuck Test"); // bool(true)
var_dump(isset($undefined) == "Chuck Test"); // bool(false)
var_dump(isset($undefined) && $undefined == "Chuck Test"); // bool(false)
it looks like they are equivalent but they aren't:
var_dump(isset($var) == "Chuck Testa"); // bool(true) !!!
var_dump(isset($var) && $var == "Chuck Testa"); // bool(false)
because isset() returns true
or false
, and an non-empty string compared to true
results in true
.
So better use the isset($var) && $var == "Test"
variant, because it does what you would expect.
Upvotes: 2
Reputation: 12328
The function isset()
returns true (boolean) if a variable is set. Now when you compare a boolean == "Test", it is bogus. So to check whether your variable is set and has the value of 'Test' you should use isset($var) && $var == 'Test'
. But I don't see why you should not do `$var == 'Test'. Does the interpreter complain about uninitialized variable that way?
Read the following, ask any question if you do not understand what the function isset
actually does:
http://php.net/manual/en/function.isset.php
Upvotes: 1
Reputation: 7054
The first one makes no sense. As you can see isset
returns a Boolean. So isset($var) == "Test"
as I said evaluates a bool against a string.
With the evaluation isset($var) && $var == 'Test'
PHP first checks if the variable $var is defined and then if that value is equal to the string 'test'.
Calling just $var == 'Test
without ensuring that it is set will result in an 'Undefined variable' notice. If you are not sure and don't want a noisy log then you can check with isset.
Upvotes: 2