Quote:
|
If you want to be super correct its quite useful to use if($varBool == true)
|
PHP Code:
if ($varBool === true) // actually :D
// if $varBool is equal to value and equal to type (===)
Paul, I highly suggest you stick this at the top of all of your scripts during any development:
PHP Code:
error_reporting(E_ALL);
It will clearly show why
is stupid. It doesn't run isset(), instead it tries to make a boolean decision. false, null, 0, empty string, or an empty array will all return false. I am not sure if it is only with empty() but a string containing only containing the digit zero may return false as well. Everything else will return true. However, take this complete script into consideration.
PHP Code:
<?php
if ($foo) echo 'Foo evaluated to true!';
?>
ERROR! $foo has not been set! This is something many people do not see because they have no idea about errors that go as notices (strict errors are some of them). This is why I suggested the error reporting change. You cannot reference a variable that does not exist. So how do you test if the variable exists yet? Ah ha! isset()!
PHP Code:
<?php
if (isset($foo)) echo 'Foo was set, and if it is not, I do not get an error message!';
?>
isset() does not check if a value is set, it rather checks if the variable is set.
Another misconception is forms. If someone does not fill out a field, the variable is still set.. however, the value is an empty string. See that word "empty"? empty is another language construct (like isset) that will return true or false. When does it return false? When the variable is not set (like isset), when the variable is one of; null, false, 0, empty string, empty array, or a string with the digit 0, and everything else returns true.
PHP Code:
<?php
if (isset($_POST['name'])) {
// If the form was submitted this is ALWAYS reached
}
if (!empty($_POST['name'])) {
// If the form was submitted but the "name" field was empty, this will be reached
}
?>
Keep in mind that using empty() and isset() on unset variables (like my if($foo) test) will not produce any errors. Why? Because these are not functions, they are language constructs, and they can be special in that way.
So the difference between
PHP Code:
if ($foo)
// and
if (!empty($foo))
is simply that one could produce an error if $foo does not exist while the other will not.
I hope this clears some things up...