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 is keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same object. The test returns False if they are not the same object, even if the two objects are 100% equal. Use the == operator to test if two variables are equal.
It checks whether $variable evaluates to true . There are a couple of normal values that evaluate to true , see the PHP type comparison tables. if ( ) can contain any expression that ultimately evaluates to true or false .
The is_bool() function checks whether a variable is a boolean or not. This function returns true (1) if the variable is a boolean, otherwise it returns false/nothing.
The is_string() function checks whether a variable is of type string or not. This function returns true (1) if the variable is of type string, otherwise it returns false/nothing.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With