How exactly does if($variable) work? [duplicate]
Solution 1:
The construct if ($variable)
tests to see if $variable
evaluates to any "truthy" value. It can be a boolean TRUE
, or a non-empty, non-NULL value, or non-zero number. Have a look at the list of boolean evaluations in the PHP docs.
From the PHP documentation:
var_dump((bool) ""); // bool(false)
var_dump((bool) 1); // bool(true)
var_dump((bool) -2); // bool(true)
var_dump((bool) "foo"); // bool(true)
var_dump((bool) 2.3e5); // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array()); // bool(false)
var_dump((bool) "false"); // bool(true)
Note however that if ($variable)
is not appropriate to use when testing if a variable or array key has been initialized. If it the variable or array key does not yet exist, this would result in an E_NOTICE Undefined variable $variable
.
Solution 2:
If converts $variable
to a boolean, and acts according to the result of that conversion.
See the boolean docs for further information.
To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
Solution 3:
The following list explains what is considered to evaluate to false
in PHP:
- the boolean FALSE itself
- the integer 0 (zero)
- the float 0.0 (zero)
- the empty string, and the string "0"
- an array with zero elements
- an object with zero member variables (PHP 4 only)
- the special type NULL (including unset variables)
- SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).
source: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
In your question, a variable is evaluated inside the if()
statement. If the variable is unset, it will evaluate to false according to the list above. If it is set, or has a value, it will evaluate to true, therefore executing the code inside the if()
branch.