Are these two statements executed identically, given $thing could be of any type?
if (!empty($thing)) {
// do stuff
}
if ($thing) {
// do stuff
}
I'm aware I could try it, but I'm not sure I'd catch all the edge cases... I'm afraid in some situations they would execute identically, but not all.
If $thing is undefined, then if ($thing) would throw a (non-fatal) error while if (!empty($thing)) would return false.
See empty() in the PHP documentation.
The relevant manual pages are Converting to boolean and, of course, empty(). For empty() we have this:
A variable is considered empty if it does not exist or if its value equals FALSE
So they're fully equivalent except in the situation where a variable does not exist. And in that case:
var_dump( empty($not_exists), (bool)$not_exists );
... we get:
bool(true)
bool(false)
... (among the corresponding notice) because:
the following values are considered FALSE: [...] unset variables
if (empty($foo)) is the negative of if ($foo), which can easily be seen in the type comparison tables, which means that on the lowest level:
if (!empty($foo))
is logically the same as
if ($foo)
However, for undefined variables, or array indices, if ($foo) and if ($foo['bar']) will cause an E_WARNING to occur, while if (!empty($foo)) and if (!empty($foo['bar'])) will not.
To that effect, you should prefer empty and !empty in cases where the variable or index might not exist, such as with $_GET or $_POST. In cases where the variable or index should exist, you should prefer $var and !$var specifically so that the warnings thrown are tracked, as they would likely be due to bugs.
There are some differences according to the manual, for example:
$object = new stdclass;
if ($object) {} // false in PHP 4, true in PHP 5+
Also, you can only pass variables to empty, this will throw an error:
if (empty(time()) {}
// Fatal error: Can't use function return value in write context
if (time()) {} // OK
And of course, if ($var) on an uninitialized variables will produce a notice.
if ($var) is an implicit boolean conversion. See the manual for details.
http://php.net/manual/en/language.types.boolean.php
When converting to boolean, the following values are considered FALSE:
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).
Compare to empty
http://php.net/manual/en/function.empty.php
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
So they are basically the same but with a couple very subtle differences. Use both with caution, and do type checking when possible.
empty can blow up horribly in certain cases, the biggest of which is 0 values
php > $x = 0;
php > var_dump(empty($x));
bool(true)
php > $x = false;
php > var_dump(empty($x));
bool(true);
as long as you're not requiring 0/false values to pass through, then empty() works out great.
Related
So the syntax for if statements is:
if(condition){
//code to execute
}
Then why do functions when placed in place of conditions work in PHP.
In PHP (and many languages) there is no specific concept of a "condition"; the actual definition of an if statement is:
if(expression){
//code to execute
}
An "expression" is simply anything that can be evaluated and results in a value. A single value, like 42 is an expression on its own, as is a simple sum like 1 + 1. A function call like strlen('hello') is also an expression, evaluating to the result of the function; the function has to be run, which may have side effects, to determine that result. Expressions can be arbitrarily complex by linking then with operators, like strlen('hello') * 2 + 1.
Commonly in an if statement, you'd have something like $foo === $bar - this is just an expression that uses the === operator to give a boolean result, either true or false. PHP will evaluate that expression, and then decide whether to run the conditional code based on the result. The expression can be as simple or complex as you want - if(true) is valid, though not often useful, and so is if((strlen('hello') * 2 + 1) > 10).
If the result of the expression is not a boolean, PHP "coerces" it into one, as described on the manual page about the boolean type. For instance strlen($foo) evaluates to an integer, and all integers other than zero coerce to true, so if(strlen($foo)) acts like if(strlen($foo) !== 0).
As well as function calls, there are other expressions which have side effects. For instance, an assignment can also be used as an expression, evaluating to the value assigned. This lets you do things like $foo = $bar = 0; where $foo is assigned the result of running $bar = 0; which is of course 0. It also lets you put assignments inside if statements, like if ( $result = getData() ) { ... }, which is shorthand for $result = getData(); if ( $result ) { ... } This technique should be used with care, though, because at a glance it can be hard to spot the difference between = (assignment) and == (weak comparison).
The values returned in a PHP if condition are not restricted to be "strictly" Boolean, however the condition is expected to be Boolean. Why? Because all PHP variables types (inbuilt or user-defined) can be implicitly type-casted (converted automatically) to Boolean. According to the PHP manual:
To explicitly convert a value to bool, 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 bool argument.
The PHP manual also explicitly specifies the falsy values for the different variable types including user defined types with all other values not specified being truthy:
the following values are considered false:
the boolean false itself
the integer 0 (zero)
the floats 0.0 and -0.0 (zero)
the empty string, and the string "0"
an array with zero elements
the special type NULL (including unset variables)
SimpleXML objects created from attributeless empty elements, i.e. elements which have neither children nor attributes.
Every other value is considered true (including any resource and NAN).
Therefore, to explicitly answer your question:
why do functions when placed in place of conditions work in PHP?
One reason I know of, is so you can conveniently perform assignments in the conditions:
function inverse_power($base, $exp)
{
if($power = pow($base, $exp)) {
return 1/$power;
}
else {
return "logical error: you can't divide by zero";
}
}
echo inverse_power(2,1); // 0.5
echo inverse_power(0,1); // logical error: you can't divide by zero
From the above example, you see the feature saves me multiple lines of code. Note that $power is not explicitly Boolean, but will be automatically converted to Boolean only to test the condition. The actual value of $power still persists throughout the function.
Because a condition is a boolean and functions can return booleans. And for conditions to work, the condition itself has to be evaluated, so it can be a function that is executed also.
This question already has answers here:
Closed 11 years ago.
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:
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.
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.
if (true) // very direct
if (true == true) // true == true evaluates to true
if (true || true && true) // boils down to true
$foo = true;
if ($foo) // direct true
if ($foo == true) // you get the idea...
Any of these are considered to be false (so that //code to be executed would not run)
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
All other values should be true. More info at the PHP Booleans manual.
Try looking at this old extended "php truth table" to get your head around all the various potholes waiting to burst your tyres. When starting out be as explicit as you can with any comparison operator that fork your code. Try and test against things being identical rather that equal to.
It depends entirely on the value type of the object that you are checking against. In PHP each object type has a certain value that will return false if checked against. The explanation of these can be found here: http://php.net/manual/en/language.types.boolean.php Some values that evaluate to false are
float: 0.0
int: 0
boolean: false
string: ''
array: [] (empty)
object: object has 0 properties / is empty
NULL
Its a bit different from most other languages but once you get used to it it can be very handy. This is why you may see a lot of statements such as
$result = mysqli_multi_query($query) or die('Could not execute query');
A function in PHP need only return a value type that evaluates to false for something like this to work. The OR operator in PHP will not evaluated its second argument IF the first argument is true (as regardless of the second argument's output, the or statement will still pass) and lines like this will attempt to call a query and assign the result to $result. If the query fails and the function returns a false value, then the thread is killed and 'Could not execute query' is printed.
if a function successfully runs (true) or a variable exists (true) boolean the if statement will continue. Otherwise it will be ignored
In various PHP tutorials I see this syntax -
if ($_POST) {
do something
}
I want to know whether this is equivalent to either isset or !(empty) (either one) or has different properties.
It attempts to evaluate the expression and cast it to boolean.
See 'Converting to boolean' at http://php.net/manual/en/language.types.boolean.php to see which values will be equivalent to true and which to false.
It does NOT however check for array key existence (i.e. isset), so if you try if ($_GET['somekey']) but somekey does not exist, you will see PHP Notice: Undefined index: somekey and then false will be assumed.
The best practice would be to perform empty() or isset() checks manually first as fits.
Good question. You are adressing one of PHPs dark sides if you ask me.
The if statement
Like in any other language I can imagine if evaluates the parameter to either true or false.
Since PHP doesn't really know types you could put any expression as parameter which will then be casted to bool as a whole
Following values are considered to be "FALSE"
boolean FALSE
integer 0
float 0.0
empty string
string "0"
any array with zero elements
NULL e.g. unset variables or $var = null
SimpleXML objects when created from empty tags
EVERY other value or expression result is casted to bool TRUE
Now, knowing this, all we need to find out is, what an expression or function returns when executed
If no POST data is set, the following expression would be TRUE
$_POST == FALSE
The isset function
isset returns bool TRUE when the given variable is set and not null.
parameters can be variables, array elements, string offsets and data members of objects.
In PHP 5.4 they fixed the behaviour with string offsets
$var = FALSE;
isset( $var ) === TRUE;
$var === FALSE;
More here
http://de1.php.net/manual/en/function.isset.php
The empty function
Returns false when a variable is considered to be empty or does not exist.
Those values are considered empty:
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
The following values are considered to be empty:
"" (empty string)
0 (integer)
0.0 (float)
"0" (string)
NULL
FALSE
array() (empty array)
Also declared variables without value are empty
compare table
$var = FALSE;
isset($var) === TRUE;
empty($var) === TRUE;
$var === FALSE;
if ($_POST)
This will evaluate to true if there are any elements in the POST array.
if(isset($_POST))
This will always evaluate to true because the POST array is always set, but may or may not contain elements, therefore it is not equivalent to the first example.
if(!empty($_POST))
This however, is equivalent to the first example because empty() checks for contents in the array.
A good generic way of testing if the page was posted to is:
if($_SERVER['REQUEST_METHOD'] == 'POST')
$_POST:
this is used to find whether data is passed on using HTTP POST method and also extracting the variables sent through the same which are collected in an associative array
isset:
checks whether a variable is set(defined) or is NULL(undefined)
PHP.net is an invaluable source of information for figuring out the intricacies and quirks of the language.
With that said, those are not equivalent. The if statement converts the expression to a boolean value (see here for information on what is considered false).
isset is used to "determine if a variable is set and is not NULL."
empty determines whether a variable is empty, i.e., "it does not exist or if its value equals FALSE."
Best practice if you want to check the value of a variable but you aren't sure whether it is set is to do the the following:
if(isset($var) && $var) { ... }
ie check isset() AND then check the variable value itself.
The reason for this is that if you just check the variable itself, as per the example in your question, PHP will throw a warning if the variable is not set. A warning message is not a fatal error, and the message text can be suppressed, but it's generally best practice to write code in such a way that it doesn't throw any warnings.
Calling isset() will only tell you whether a variable is set; it won't tell you anything about the value of the variable, so you can't rely on it alone.
Hope that helps.
I was wondering what's the difference the two cases below, and which one is recommended?
$val = 0;
if (!$val) {
//True
}
if (empty($val) {
//It's also True
}
Have a look at the PHP type comparison table.
If you check the table, you'll notice that for all cases, empty($x) is the same as !$x. So it comes down to handling uninitialised variables. !$x creates an E_NOTICE, whereas empty($x) does not.
If you use empty and the variable was never set/created, no warning/error will be thrown.
Let see:
empty documentation:
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Booleans documentation:
When converting to boolean, the following values are considered FALSE:
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
It seems the only difference (regarding the resulting value) is how a SimpleXML instance is handled. Everything else seems to give the same result (if you invert the boolean cast of course).
This question already has answers here:
Closed 11 years ago.
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:
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.
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.
if (true) // very direct
if (true == true) // true == true evaluates to true
if (true || true && true) // boils down to true
$foo = true;
if ($foo) // direct true
if ($foo == true) // you get the idea...
Any of these are considered to be false (so that //code to be executed would not run)
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
All other values should be true. More info at the PHP Booleans manual.
Try looking at this old extended "php truth table" to get your head around all the various potholes waiting to burst your tyres. When starting out be as explicit as you can with any comparison operator that fork your code. Try and test against things being identical rather that equal to.
It depends entirely on the value type of the object that you are checking against. In PHP each object type has a certain value that will return false if checked against. The explanation of these can be found here: http://php.net/manual/en/language.types.boolean.php Some values that evaluate to false are
float: 0.0
int: 0
boolean: false
string: ''
array: [] (empty)
object: object has 0 properties / is empty
NULL
Its a bit different from most other languages but once you get used to it it can be very handy. This is why you may see a lot of statements such as
$result = mysqli_multi_query($query) or die('Could not execute query');
A function in PHP need only return a value type that evaluates to false for something like this to work. The OR operator in PHP will not evaluated its second argument IF the first argument is true (as regardless of the second argument's output, the or statement will still pass) and lines like this will attempt to call a query and assign the result to $result. If the query fails and the function returns a false value, then the thread is killed and 'Could not execute query' is printed.
if a function successfully runs (true) or a variable exists (true) boolean the if statement will continue. Otherwise it will be ignored