185

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"??

mysqllearner
  • 13,523
  • 15
  • 43
  • 43
  • 19
    @stereo `empty` is perhaps the most useful yet widely misunderstood PHP function. Learn how and when to use it. – deceze Feb 08 '10 at 09:31
  • 2
    @stereo `empty` is essentially short for `isset($var) && $var != false`. You must be holding your `empty` very weird to shoot yourself in the foot with this. ;P – deceze Feb 08 '10 at 10:50
  • @stereo 1) Where is it "inconsistent"? It works like it says on the tin. 2) Loosely comparing a variable to `false` without triggering an "undefined variable" error is useless? Oh well, guess you never do this… 3) Choosing the wrong function in a security context doesn't mean the function itself is bad, useless or inconsistent; it just means somebody chose the wrong function for the job. – deceze Feb 08 '10 at 11:27
  • RTFM http://php.net/manual/en/function.empty.php – Xavier Barbosa Jan 08 '11 at 14:45
  • 34
    @deceze - If a function is so widely misunderstood like `empty()`, then it has probably the wrong name. – martinstoeckli May 29 '13 at 07:55
  • @martinstoeckli I'd love to hear a suggestion for a better one. :) – deceze May 29 '13 at 08:03
  • 1
    @deceze - Good reply - of course finding a good name is the hard work. The function does a bit too much, so it cannot be easy to find a name. Since mostly the 0 is the problem in understanding, a name like `emptyOrZero()` would be better, but this would not say anything about `FALSE` or `'0.0'` (which is handled different from `0.0`). I suspect this function was written to interpret the input of HTML input elements, so why not write a function that says so, maybe the opposite: `isHtmlInputSet()`. Anyway, we can't change it, so it is as you said, learn how it works :-) – martinstoeckli May 29 '13 at 08:31
  • @martinstoeckli `empty` does the same comparison as `== false`, but doesn't care whether a variable exists or not. So, `falsey`? `loosely_false_or_not_set`? I think `empty` works just fine, you just have to **learn** what it does and not *assume*; just as with any other function. :) – deceze May 29 '13 at 08:41
  • Just a note: @deceze's 2nd comment is not correct. If a variable is not set OR false, it WILL return empty. So instead it's more like `empty($var) := !isset($var) || $var === false || $var === 0 || ...` I think xe meant to say that empty returns *false* if `isset($var) && $var != false`. – Chris Middleton Aug 19 '14 at 19:11
  • When a variable is guaranteed to exist (be declared), then `!empty()` is never the appropriate tool. – mickmackusa Jun 05 '21 at 06:30
  • I think the problem is not the name but its functionality. I would imagine empty to be used with strings or arrays. It should only check if a string is empty (zero length) or array has no elements. That would be more appropriate. – Whip Dec 06 '22 at 10:26

18 Answers18

241

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.

relipse
  • 1,730
  • 1
  • 18
  • 24
deceze
  • 510,633
  • 85
  • 743
  • 889
  • So, i must check like this: if(isset($var) && $var != 0){ Do Something} ?? – mysqllearner Feb 08 '10 at 09:22
  • 1
    @mysql For this case you might as well use `!empty($var)`, but note that that's not the same as what you wrote in the question. What to use depends entirely on what values you want to regard as `true`. Just compare the differences between `isset` and `empty` and choose the right combination for the right situation. – deceze Feb 08 '10 at 09:25
  • 8
    @mysqllearner: `isset` returns `True` if `$var=0`. But what you mean with `if(isset($var) && $var != 0)` is the same as `empty` – Felix Kling Feb 08 '10 at 09:26
  • @mysqllearner isset detects if it is NOT empty. to check if it is empty, use !isset instead. –  Jan 13 '13 at 06:11
  • empty() should be replaced by an "is_empty_string()" to erase confusion. Most people don't consider 0 or "0" to be empty, but rather null and "" are 'empty'. The former just represent no value. – Deji May 12 '16 at 08:30
  • 2
    I think it's rather logical to think that if strlen() > 0, empty() should != true – Deji May 12 '16 at 08:31
  • @Deji `empty`'s job is to do a loose comparison to `false` while not triggering an error should the variable not exist at all. Summing that up in one word is pretty tricky, "`empty`" isn't too bad IMO. "`is_empty_string`" already exists: `=== ''`. – deceze May 12 '16 at 08:32
  • @deceze I already know what it's job is, I was stating what it's job should be, going by what it sounds like it should be. And your idea of `is_empty_string` isn't any good, it would return `false` for `is_empty_string(false)` - which is what `empty` already does... What I'm suggesting is that anything which, when converted to a string, is empty, is empty. Anything else isn't, because it conveys a value which has to be actually written in a human language. – Deji May 12 '16 at 09:30
  • And seriously, '0' is soooo different from 0, it should NEVER be treated the same. Implicit casting may be a strength for PHP, but how it has decided to go about it in some of the small details is rather annoying. – Deji May 12 '16 at 09:31
  • 1
    @Deji Since PHP has its roots as a web language, and values in HTTP requests are always strings, `'0'` is being treated as equivalent to `0`. That's a core design philosophy of PHP. **I agree that this is an extremely debatable choice,** however, I'm not here to debate that choice with you. Within PHP's logic, `empty` as equivalent to `== false` minus notices is fine IMO. That some things should be very different in PHP than they are is a different topic. – deceze May 12 '16 at 10:00
  • @deceze I'm aware of this too. I wasn't here to do anything but raise the point that it's an extremely debatable choice. – Deji May 12 '16 at 11:51
  • 1
    0.0 (0 as a float) also is empty – relipse Jun 12 '19 at 15:10
  • 1
    Useful to add that multiple zeroes in a string are considered not empty. `empty("00") > false` as well as `empty("0.0") > false`. – Dostrelith Aug 10 '20 at 10:33
  • If `empty` is loose, why not add an `is_strict_empty` that doesn't equate "0" with being empty? I agree with @Deji that if strlen() > 0 then that's not really empty. Only being in PHP every 3-6 months, some things don't always stick, and stupid me thought "0" wouldn't be empty. Maybe now, after writing this, it'll stick. :) – Keith DC Feb 10 '21 at 10:07
  • @Keith Given what `empty` does, "`is_strict_empty`" makes little sense. Yes, non-empty strings being *falsey* is a pitfall in PHP. It makes sense when looked at from the right angle, but certainly opens up a lot of pitfalls… – deceze Feb 10 '21 at 10:09
98

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

Pikamander2
  • 7,332
  • 3
  • 48
  • 69
Dan Soap
  • 10,114
  • 1
  • 40
  • 49
53

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";
}
TerryA
  • 58,805
  • 11
  • 114
  • 143
Khandad Niazi
  • 2,326
  • 3
  • 25
  • 22
15

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.

Shahzad Barkati
  • 2,532
  • 6
  • 25
  • 33
Calin Rusu
  • 187
  • 1
  • 5
  • just add an @strlen to omit the error log, just in case... to not create a big log – Miguel Jun 08 '15 at 12:06
  • Why would you put `@strlen`. As long as you pass a variable it shouldn't output an error. If your strlen is empty it will record the value as 0. – sketchthat Feb 05 '16 at 01:06
  • 2
    If the variable is unset, I believe you will get an error. – Evren Yurtesen Jul 02 '16 at 07:19
  • Direct ```strlen()``` check doesn't work for non-string values with ```strict_types=1```, you have to cast it to a string first: ```strlen("".$var)```. The cast even nicely handles nulls and booleans (true is ```"1"```, while false and null is ```""```). – mikiqex Mar 24 '21 at 18:20
12

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!';
}
Oliver Williams
  • 5,966
  • 7
  • 36
  • 78
6

empty() returns true for everything that evaluates to FALSE, it is actually a 'not' (!) in disguise. I think you meant isset()

soulmerge
  • 73,842
  • 19
  • 118
  • 155
6

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.

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Elzo Valugi
  • 27,240
  • 15
  • 95
  • 114
4

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
bhu1st
  • 1,282
  • 11
  • 23
4

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']=''
2

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.

codaddict
  • 445,704
  • 82
  • 492
  • 529
2

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

Adam Kiss
  • 11,811
  • 9
  • 48
  • 81
2

You need to use isset() to check whether value is set.

Veershetty
  • 21
  • 1
  • Hi @Veershetty, welcome to Stack Overflow. Thanks for you answer however it doesn't seem to add anything new over existing, more detailed answers. Either edit the answer to add detail which is missing from other answers or consider deleting your answer if it adds nothing new. – Gricey May 15 '19 at 04:45
1
if (empty($var) && $pieces[$var] != '0') {
//do something
}

In my case this code worked.

Cherrish
  • 11
  • 1
1

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.

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
arash
  • 11
  • 1
0

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.

Saad
  • 1,047
  • 2
  • 19
  • 32
0

use only ($_POST['input_field_name'])!=0 instead of !($_POST['input_field_name'])==0 then 0 is not treated as empty.

0

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.

Community
  • 1
  • 1
0

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.

Sayed Mohd Ali
  • 2,156
  • 3
  • 12
  • 28