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.
Related
For the record, I know the solution is to use === instead of == .
I'm just wondering what the logic behind it is. How is it logical that 'hello' can equal TRUE?
$var = TRUE;
if($var == 'hello'){
echo 'match';
}
else{
echo 'no match';
}
The solution has been discussed, but I haven't seen any real explanation.
String value equals true
== compares just the values of the variables whereas === compares variable values and type. so for an example:
1 == 1: true
1 === "1": false // "1" is a string and 1 is an integer
when asking if a string == true, you are essientially asking if it is set. Similar functionality is behind the isset() method.
If you were to compare "hello" === true. This would be false as they are of different type and "hello" would HAVE to equal "hello"
When using == operator think in falsy and truthy terms.
So:
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integers 0 and -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 empty tags
-1 is considered TRUE, like any other non-zero (whether negative or positive) number!
Every other value is considered TRUE (including any resource and NAN).
#see: https://www.php.net/manual/en/language.types.boolean.php
I eval $var using
if(empty($_GET['var'])){
...
}
I take TRUE from
https://myweb.com/?var=0
I take FALSE from
https://myweb.com/?var=00
The empty pseudo-function shares its logic with casting to boolean - if something is equivalent to "false", it is considered "empty".
The list of values which are considered "empty" is intended to be helpful, but is occasionally confusing, because there isn't really one perfect answer. Starting off with integers, it seems reasonable that 0 is "empty", but for instance 1 is not. Because user input almost always comes in the form of strings (particularly on the web, where PHP is most at home), it's also useful for the string "0" to behave the same as the integer 0.
On the face of it, "00" should also be equivalent to 0, and therefore "empty", but now things start getting messy: if you convert the string "hello" to an integer, that is also 0, so is "hello" also empty? That wouldn't be very useful.
The truth is, casts such as this can only really work one of two ways:
Throw an error on any conversion which is not 100% unambiguous.
Pick a set of compromises which is mostly useful, but not entirely consistent.
PHP picked the second route, and the difference between empty("0") and empty("00") is one of the side effects of the particular compromise chosen. Other languages which took a similar route (e.g. Perl, JavaScript) have different compromises, with different surprising outcomes.
See also my answer to a similar question here.
Because 0 gives empty in PHP if you check without type, but I think 00 type-cast to a string value and thus it's not empty.
You can strict check with type via the operator ===
I think it's probably because you are receiving the 00 as string value in your code. Because 0 and 00 are both considered as empty by the empty function in PHP. Try executing the code below in one of your PHP's to understand better. You can even check out the sandbox link.
<?php
$a = 0;
$b = 00;
$c = '00';
if(empty($a)) echo 'empty a';
if(empty($b)) echo 'empty b';
if(empty($c)) echo 'empty c';
?>
Check the documentation of empty() function, there are a list of values that are considered as empty by it.
The empty() function checks whether a variable is empty or not.
This function returns false if the variable exists and is not empty,
otherwise it returns true.
The following values evaluates to empty:
0
0.0
"0"
""
NULL
FALSE
array()
Additionally, when you are dealing with numeric check, you should always typecast the value to integer and then compare if it's 0 or not. This would be the ideal approach.
<?php
$a = 0;
$b = '0';
$c = '00';
$d = 1;
$e = '1';
if(!intval($a)) echo 'empty a ';
if(!intval($b)) echo 'empty b ';
if(!intval($c)) echo 'empty c ';
if(!intval($d)) echo 'empty d ';
if(!intval($e)) echo 'empty e ';
?>
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.
I came across this code in a php database class:
if( !$this->_Link_ID )
Link_ID is an integer.
So does this code just check if Link_ID is not 0?
I know from experience that if a variable is type Boolean, you can just test the var like
$myBoolean = true;
if ($myBoolean){
// code
}
I didn't realise this can be done for integers.
So how is if( !$this->_Link_ID ) evaluated?
It checks if the integer is zero if it's integer. It also evaluates to truth if it's set to null and if it's unset, but in the latter case it also spits out a warning. if there was no negation, that would be a test for non-zero.
For more details see: converting to boolean:
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).
this is simply a silly way of check for non-zero,if LINK_ID is 0 or null or false ,it will
give true(please notice the '!') ,else if the LINK_iD is any thing it will give false
LINK_iD = 1 ,if (!LINK_ID) //this will give false
LINK_ID = 0 if (!LINK_iD) //this will give true
if( !$this->_Link_ID )
will return true if the value of $this->_Link_ID is 0, empty string or null.
If you want to check explicitly for "0" then you should use the triple equal ("===" or "!==") to test the value. like so
if($this->_Link_ID === 0)
or
if($this->_Link_ID === false)
if you only want it to return true for false, but not "0".
if (!$this->_Link_ID) will be true if $this->_Link_ID is not 0, and false if it is 0.
In PHP, you can test anything as a Boolean. A Boolean can be represented as 0 or 1, with 0 being false and 1 being true. In PHP, anything that is not 0 will be true, and anything that is 0 will be false. For example:
$string = 'This is a test.'
if ($string) echo 'Evaluated to true!';
Will print 'Evaluated to true!'. If $string does not exist, it will print nothing.
you should use
if (!is_int($var))
because
if (!$var)
checks if $var is not 0 or false
and if you want to check if $var exists you need to use this:
if (isset($var))
not only integers though
Here goes an explanation http://php.net/manual/en/language.types.type-juggling.php
And here goes a cheat-sheet http://www.php.net/manual/en/types.comparisons.php
Are the below two statements similar?
if (isset($someValue) && $someValue != '')
and
if(!empty($someValue]))
No, they are not the same. Yes, they are similar. The first one checks if the 'someValue' is set and not equal to null plus whether it is not empty string. The second one is true if $_GET['act'] is not set or is on the list of variables treated as empty and listed on documentation page.
The following example from the same documentation page should fill any gaps:
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
Kind of similar except 0 value.
According to http://us3.php.net/empty
$var = "0";
(!empty($var)) === false;
(isset($var) && $var!='') === true;
As you write it, they're actually almost the opposite, but I'll just assume you mean isset($_GET[someValue]) and !empty.
In that case no, they're not the same. In the first line you are checking for an empty string, but for example a zero value would pass. However, a zero value counts as empty.
Similar but not the same. Empty will return true if $_GET['act'] is equal to any of the following:
"" (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)
Where as the first one only checks to see if the variable has been created and isn't equal to an empty string.