Why this line of code does not work in php like as in JS:
$id = [];
$id = null || [];
if (count($id)) {
echo 'd';
}
Why $id still is null instead empty array []? Therefore count() gives an error.
In PHP, logical operators like || always return a boolean, even if given a non-boolean output.
So your statement is evaluated as "is either null or [] truthy?" Since both null and an empty array evaluate to false, the result is boolean false.
There are however two operators which would do something similar to JS's ||:
$a ?: $b is short-hand for $a ? $a : $b; in other words, it evaluates to $a if it's "truthy", or $b if not (this is documented along with the ternary operator for which it is a short-hand)
$a ?? $b is similar, but checks for null rather than "truthiness"; it's equivalent to isset($a) ? $a : $b (this is called the null-coalescing operator)
<?php
// PHP < 7
$id = isset($id) ? $id : [];
// PHP >= 7
$id = $id ?? [];
As of PHP 7 and above
Null Coalesce Operator
Another helpful link
Watch out!
I find PHP's handling of empty to be highly questionable:
empty($unsetVar) == true (fabulous, no need to check isset as warning is suppressed!)
empty(null) == true
empty('') == true
All fine, until we get to this nonsense:
empty(false) == true. Wait, WHAT???
You've GOT to be kidding me. In no world should false be taken to mean the same thing as no value at all! There's nothing "empty" about a false assertion. And due to this logical fallacy, you cannot use empty to check ANY variable that might have a VALUE of false.
In my projects, I use a static method:
public static function hasValue($value) {
return isset($value) && !is_null($value) && $value !== '';
}
Of course, using this method, I no longer get the free warning suppression provided by empty, so now I'm also forced to remember to call the method above with the notice/warning suppression operator #:
if(self::hasValue(#$possiblyUnsetVar)) {}
Very frustrating.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reference - What does this symbol mean in PHP?
Getting confused with empty, isset, !empty, !isset
In PHP what is the difference between:
if(!isset)
if(isset)
Same with if(!empty) and if(empty)?
What does the "!" character mean?
! is the logical negation or NOT operator. It reverses the sense of the logical test.
That is:
if(isset) makes something happen if isset is logical True.
if(!isset) makes something happen if isset is logical False.
More about operators (logical and other types) in the PHP documentation. Look up ! there to cement your understanding of what it does. While you're there, also look up the other logical operators:
&& logical AND
|| logical OR
xor logical EXCLUSIVE-OR
Which are also commonly used in logic statements.
The ! character is the logical "not" operator. It inverts the boolean meaning of the expression.
If you have an expression that evaluates to TRUE, prefixing it with ! causes it evaluate to FALSE and vice-versa.
$test = 'value';
var_dump(isset($test)); // TRUE
var_dump(!isset($test)); // FALSE
isset() returns TRUE if the given variable is defined in the current scope with a non-null value.
empty() returns TRUE if the given variable is not defined in the current scope, or if it is defined with a value that is considered "empty". These values are:
NULL // NULL value
0 // Integer/float zero
'' // Empty string
'0' // String '0'
FALSE // Boolean FALSE
array() // empty array
Depending PHP version, an object with no properties may also be considered empty.
The upshot of this is that isset() and empty() almost compliment each other (they return the opposite results) but not quite, as empty() performs an additional check on the value of the variable, isset() simply checks whether it is defined.
Consider the following example:
var_dump(isset($test)); // FALSE
var_dump(empty($test)); // TRUE
$test = '';
var_dump(isset($test)); // TRUE
var_dump(empty($test)); // TRUE
$test = 'value';
var_dump(isset($test)); // TRUE
var_dump(empty($test)); // FALSE
$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';
}
Edit:
here is a test case for you:
$p = false;
echo isset($p) ? '$p is setted : ' : '$p is not setted : ';
echo empty($p) ? '$p is empty' : '$p is not empty';
echo "<BR>";
$p is setted : $p is empty
which is better?
if (!empty($val)) { // do something }
and
if ($val) { // do something }
when i test it with PHP 5, all cases produce the same results. what about PHP 4, or have any idea which way is better?
You should use the empty() construct when you are not sure if the variable even exists. If the variable is expected to be set, use if ($var) instead.
empty() is the equivalent of !isset($var) || $var == false. It returns true if the variable is:
"" (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)
Read the manual:
empty() is the opposite of (boolean) var, except that no warning is
generated when the variable is not set.
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.
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.