In my case, the variables $nr and $str can have only two possible values. $nr can contain integer/numeric or null, not "null" between double quotes. $str can contain a string value or null. Can I just check if the variables are empty or not like this?
if ($nr) {}
if (! $nr) { return; }
if ($str) {}
if (! $str) { return; }
I think the answer is Yes but some code snippets of others made me doubt about that because they check it as following.
if (empty($var) || "" === $var || null === $var) { return; }}
I think this is unnecessary. To be specific, it is in PHP7.4.
You can check https://www.php.net/manual/en/types.comparisons.php to see what can be used to check if something is truthy or falsy. Below is the table of the link before condensed into a table of things you can plug into an if statement and what the results will be.
Before utilizing these tables, it's important to understand types and their meanings. For example, "42" is a string while 42 is an int. false is a bool while "false" is a string.
Expression
bool : if($x)
$x = "";
false
$x = null;
false
var $x;
false
$x is undefined
false
$x = array();
false
$x = array('a', 'b');
true
$x = false;
false
$x = true;
true
$x = 1;
true
$x = 42;
true
$x = 0;
false
$x = -1;
true
$x = "1";
true
$x = "0";
false
$x = "-1";
true
$x = "php";
true
$x = "true";
true
$x = "false";
true
if ($var)/if (!$var) simply check for truthy/falsey values respectively (they're complimentary opposites, which one you choose is merely a question of which makes more sense in your flow). Falsey values in PHP are:
false
null
0, -0, 0.0, -0.0
"0" (0 as a string)
"" (empty string)
array() (empty array)
empty SimpleXML objects (interesting special case; thanks Obama! 🤔)
Everything else is truthy.
So, if none of your desired values fall into this list and all of your undesired values are in this list, then a simple if ($var)/if (!$var) will do just fine. If your desired/undesired list does not happen to align with this and you want some of column A but also some of column B, then you need to do more specific and complicated checks.
The only time you'll want to use emtpy is if the variable you're checking may legitimately not exist. empty($var) is just !$var, but doesn't raise an error if $var doesn't exist at all. That's its only purpose, and you do not want to suppress error reporting unless you have to. In a properly written program where you declare your variables properly, there should be very very little use for empty, since you should know what variables exist and which don't.
Related
What does the double not operator do in PHP?
For example:
return !! $row;
What would the code above do?
It's not the "double not operator", it's the not operator applied twice. The right ! will result in a boolean, regardless of the operand. Then the left ! will negate that boolean.
This means that for any true value (numbers other than zero, non-empty strings and arrays, etc.) you will get the boolean value TRUE, and for any false value (0, 0.0, NULL, empty strings or empty arrays) you will get the boolean value FALSE.
It is functionally equivalent to a cast to boolean:
return (bool)$row;
It's the same (or almost the same - there might be some corner case) as casting to bool. If $row would cast to true, then !! $row is also true.
But if you want to achieve (bool) $row, you should probably use just that - and not some "interesting" expressions ;)
It means if $row has a truthy value, it will return true, otherwise false, converting to a boolean value.
Here is example expressions to boolean conversion from php docs.
Expression Boolean
$x = ""; FALSE
$x = null; FALSE
var $x; FALSE
$x is undefined FALSE
$x = array(); FALSE
$x = array('a', 'b'); TRUE
$x = false; FALSE
$x = true; TRUE
$x = 1; TRUE
$x = 42; TRUE
$x = 0; FALSE
$x = -1; TRUE
$x = "1"; TRUE
$x = "0"; FALSE
$x = "-1"; TRUE
$x = "php"; TRUE
$x = "true"; TRUE
$x = "false"; TRUE
"not not" is a convenient way in many languages for understanding what truth value the language assigns to the result of any expression. For example, in Python:
>>> not not []
False
>>> not not [False]
True
It can be convenient in places where you want to reduce a complex value down to something like "is there a value at all?".
Another more human, maybe simpler, way to 'read' the not not:
The first '!' does 2 things: 'convert' the value to boolean, then output its opposite. So it will give true if the value is a 'falsy' one.
The second '!' is just to output the opposite of the first.
So, basically, the input value can be anything, maybe a string, but you want a boolean output, so use the first '!'. At this point, if you want TRUE when the input value is 'falsy', then stop here and just use a single '!'; otherwise if you want TRUE when the input value is 'truthy', then add another '!'.
Lets look at
!$a;
Rather than interpreting the ! operator as as taking the
Boolean opposite of the value to its right
read
take the Boolean opposite of the expression to its right
In this case
$a;
could be an expression
so to is
!$a;
so is
!!$a;
and
!!!$a;
and so on, as each of these is a valid expression, the ! operator can be prepended to each of them.
I've always done this: if ($foo !== $bar)
But I realized that if ($foo != $bar) is correct too.
Double = still works and has always worked for me, but whenever I search PHP operators I find no information on double =, so I assume I've always have done this wrong, but it works anyway. Should I change all my !== to != just for the sake of it?
== and != do not take into account the data type of the variables you compare. So these would all return true:
'0' == 0
false == 0
NULL == false
=== and !== do take into account the data type. That means comparing a string to a boolean will never be true because they're of different types for example. These will all return false:
'0' === 0
false === 0
NULL === false
You should compare data types for functions that return values that could possibly be of ambiguous truthy/falsy value. A well-known example is strpos():
// This returns 0 because F exists as the first character, but as my above example,
// 0 could mean false, so using == or != would return an incorrect result
var_dump(strpos('Foo', 'F') != false); // bool(false)
var_dump(strpos('Foo', 'F') !== false); // bool(true), it exists so false isn't returned
!== should match the value and data type
!= just match the value ignoring the data type
$num = '1';
$num2 = 1;
$num == $num2; // returns true
$num === $num2; // returns false because $num is a string and $num2 is an integer
$a !== $b TRUE if $a is not equal to $b, or they are not of the same type
Please Refer to http://php.net/manual/en/language.operators.comparison.php
You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php
It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.
Code will explain more:
$var = 0;
if (!empty($var)){
echo "Its not empty";
} else {
echo "Its empty";
}
The result returns "Its empty". I thought empty() will check if I already set the variable and have value inside. Why it returns "Its empty"??
http://php.net/empty
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)
Note that this is exactly the same list as for a coercion to Boolean false. empty is simply !isset($var) || !$var. Try isset instead.
I was wondering why nobody suggested the extremely handy Type comparison table. It answers every question about the common functions and compare operators.
A snippet:
Expression | empty($x)
----------------+--------
$x = ""; | true
$x = null | true
var $x; | true
$x is undefined | true
$x = array(); | true
$x = false; | true
$x = true; | false
$x = 1; | false
$x = 42; | false
$x = 0; | true
$x = -1; | false
$x = "1"; | false
$x = "0"; | true
$x = "-1"; | false
$x = "php"; | false
$x = "true"; | false
$x = "false"; | false
Along other cheatsheets, I always keep a hardcopy of this table on my desk in case I'm not sure
In case of numeric values you should use is_numeric function:
$var = 0;
if (is_numeric($var))
{
echo "Its not empty";
}
else
{
echo "Its empty";
}
Use strlen() instead.
I ran onto the same issue using 1/0 as possible values for some variables.
I am using if (strlen($_POST['myValue']) == 0) to test if there is a character or not in my variable.
I was recently caught with my pants down on this one as well. The issue we often deal with is unset variables - say a form element that may or may not have been there, but for many elements, 0 (or the string '0' which would come through the post more accurately, but still would be evaluated as "falsey") is a legitimate value say on a dropdown list.
using empty() first and then strlen() is your best best if you need this as well, as:
if(!empty($var) && strlen($var)){
echo '"$var" is present and has a non-falsey value!';
}
From a linguistic point of view empty has a meaning of without value. Like the others said you'll have to use isset() in order to check if a variable has been defined, which is what you do.
empty() returns true for everything that evaluates to FALSE, it is actually a 'not' (!) in disguise. I think you meant isset()
To accept 0 as a value in variable use isset
Check if variable is empty
$var = 0;
if ($var == '') {
echo "empty";
} else {
echo "not empty";
}
//output is empty
Check if variable is set
$var = 0;
if (isset($var)) {
echo "not empty";
} else {
echo "empty";
}
//output is not empty
It 's working for me!
//
if(isset($_POST['post_var'])&&$_POST['post_var']!==''){
echo $_POST['post_var'];
}
//results:
1 if $_POST['post_var']='1'
0 if $_POST['post_var']='0'
skip if $_POST['post_var']=''
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but
without a value in a class)
From PHP Manual
In your case $var is 0, so empty($var) will return true, you are negating the result before testing it, so the else block will run giving "Its empty" as output.
From manual:
Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string) NULL
FALSE array() (an empty array) var
$var; (a variable declared, but
without a value in a class)
More: http://php.net/manual/en/function.empty.php
You need to use isset() to check whether value is set.
Actually isset just check if the variable sets or not.In this case if you want to check if your variable is really zero or empty you can use this example:
$myVar = '';
if (empty($myVar))
{
echo "Its empty";
}
echo "<br/>";
if ($myVar===0)
{
echo "also zero!";
}
just for notice $myVar==0 act like empty function.
if (empty($var) && $pieces[$var] != '0') {
//do something
}
In my case this code worked.
empty should mean empty .. whatever deceze says.
When I do
$var = '';
$var = '0';
I expect that var_dump(empty($var)); will return false.
if you are checking things in an array you always have to do isset($var) first.
use only ($_POST['input_field_name'])!=0 instead of !($_POST['input_field_name'])==0 then 0 is not treated as empty.
Not sure if there are still people looking for an explanation and a solution. The comments above say it all on the differences between TRUE / FALSE / 1 / 0.
I would just like to bring my 2 cents for the way to display the actual value.
BOOLEAN
If you're working with a Boolean datatype, you're looking for a TRUE vs. FALSE result; if you store it in MySQL, it will be stored as 1 resp. 0 (if I'm not mistaking, this is the same in your server's memory).
So to display the the value in PHP, you need to check if it is true (1) or false (0) and display whatever you want: "TRUE" or "FALSE" or possibly "1" or "0".
Attention, everything bigger (or different) than 0 will also be considered as TRUE in PHP. E.g.: 2, "abc", etc. will all return TRUE.
BIT, TINYINT
If you're working with a number datatype, the way it is stored is the same.
To display the value, you need to tell PHP to handle it as a number. The easiest way I found is to multiply it by 1.
proper example. just create int type field( example mobile number) in the database and submit an blank value for the following database through a form or just insert using SQL. what it will be saved in database 0 because it is int type and cannot be saved as blank or null. therefore it is empty but it will be saved as 0. so when you fetch data through PHP and check for the empty values. it is very useful and logically correct.
0.00, 0.000, 0.0000 .... 0.0...0 is also empty and the above example can also be used for storing different type of values in database like float, double, decimal( decimal have different variants like 0.000 and so on.
What does the double not operator do in PHP?
For example:
return !! $row;
What would the code above do?
It's not the "double not operator", it's the not operator applied twice. The right ! will result in a boolean, regardless of the operand. Then the left ! will negate that boolean.
This means that for any true value (numbers other than zero, non-empty strings and arrays, etc.) you will get the boolean value TRUE, and for any false value (0, 0.0, NULL, empty strings or empty arrays) you will get the boolean value FALSE.
It is functionally equivalent to a cast to boolean:
return (bool)$row;
It's the same (or almost the same - there might be some corner case) as casting to bool. If $row would cast to true, then !! $row is also true.
But if you want to achieve (bool) $row, you should probably use just that - and not some "interesting" expressions ;)
It means if $row has a truthy value, it will return true, otherwise false, converting to a boolean value.
Here is example expressions to boolean conversion from php docs.
Expression Boolean
$x = ""; FALSE
$x = null; FALSE
var $x; FALSE
$x is undefined FALSE
$x = array(); FALSE
$x = array('a', 'b'); TRUE
$x = false; FALSE
$x = true; TRUE
$x = 1; TRUE
$x = 42; TRUE
$x = 0; FALSE
$x = -1; TRUE
$x = "1"; TRUE
$x = "0"; FALSE
$x = "-1"; TRUE
$x = "php"; TRUE
$x = "true"; TRUE
$x = "false"; TRUE
"not not" is a convenient way in many languages for understanding what truth value the language assigns to the result of any expression. For example, in Python:
>>> not not []
False
>>> not not [False]
True
It can be convenient in places where you want to reduce a complex value down to something like "is there a value at all?".
Another more human, maybe simpler, way to 'read' the not not:
The first '!' does 2 things: 'convert' the value to boolean, then output its opposite. So it will give true if the value is a 'falsy' one.
The second '!' is just to output the opposite of the first.
So, basically, the input value can be anything, maybe a string, but you want a boolean output, so use the first '!'. At this point, if you want TRUE when the input value is 'falsy', then stop here and just use a single '!'; otherwise if you want TRUE when the input value is 'truthy', then add another '!'.
Lets look at
!$a;
Rather than interpreting the ! operator as as taking the
Boolean opposite of the value to its right
read
take the Boolean opposite of the expression to its right
In this case
$a;
could be an expression
so to is
!$a;
so is
!!$a;
and
!!!$a;
and so on, as each of these is a valid expression, the ! operator can be prepended to each of them.
I know this question is not really important.. however I've been wondering:
Which of the following IF statements is the best and fastest to use?
<?php
$variable = true;
if($variable === true)
{
//Something
}
if($variable)
{
// Something
}
?>
I know === is to match exactly the boolean value. However is there really any improvement?
Using if ($var === true) or if ($var) is not a question of style but a question of correctness. Because if ($var) is the same as if ($var == true). And == comparison doesn’t check the type. So 1 == true is true but 1 === true is false.
As far as speed, I agree with Niels, it's probably negligible.
As far as which if statement is best to test with, the answer probably depends on the expected casting and values $variable can have.
If $variable is using 0 and 1 as a true/false flag then if ( $variable ) or if ( !$variable ) would work, but if it's an integer result as in strpos() you'll run into problems ... if possible, I'd recommend using an actual boolean value rather than 0 / 1.
... maybe this will help clarify; comment out the variations of $var to see the various results.
<?php
$var = true;
$var = 1;
$var = false;
$var = 0;
if ( $var ) {
echo 'var = true <br />';
}
if ( $var === true ) {
echo 'var is a boolean and = true';
}
if ( !$var ) {
echo 'var = false <br />';
}
if ( $var === false ) {
echo 'var is a boolean and = false';
}
Just a fact:
time php -r '$r = true; for($i = 0; $i < 10000000; $i++) { if($r == true) {} }'
time php -r '$r = true; for($i = 0; $i < 10000000; $i++) { if($r) {} }'
The second one is faster than the first.
=== is really helpful in strstr/stristr when the first needle is in position 0 in the haystack. If you don't use === or !== you could have a bug on your hands.
$str = "four score and...";
$position = strstr($str,'four');
if($position===FALSE) return FALSE;
I'm not really deep into the technical stuff of PHP, but in the first case
if($variable === true)
$variable has to have the exact same type as true for the if statement to be true. In other words, $variable has not only to resolve to true, but also has to be a boolean. So that's 2 operations, value-checking and type-checking.
In the second case
if($variable)
$variable only has to resolve to true. So only value checking occurs. I infer that that takes the computer a little less time.
Practically speaking: the differences in speed are probably negligible.