How exactly does if($variable) work?
Possible Duplicate:
Regarding if statements in PHP
In PHP scripts - what does an if statement like this check for?
<?php if($variable){ // code to be executed } ?>
I've seen it used in scripts several times, and now I really want to know what it "looks for". It's not missing anything; it's just a plain variable inside an if statement... I couldn't find any results about this, anywhere, so obviously I'll look stupid posting this.
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
.
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.
The following list explains what is considered to evaluate to false
in PHP:
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.
上一篇: )在返回命令中的用法