Note on the selfmade empty function below:
function_exists() returns false on language constructs and empty is a language construct.
empty
(PHP 4, PHP 5)
empty — Determine whether a variable is empty
Parameters
- var
-
Variable to be checked
Note: empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).
empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.
Return Values
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)
ChangeLog
| Version | Description |
|---|---|
| PHP 5 |
As of PHP 5, objects with no properties are no longer considered empty. |
| PHP 4 |
As of PHP 4, The string value "0" is considered empty. |
Examples
Example #1 A simple empty() / isset() comparison.
<?php
$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';
}
?>
Notes
Note: Because this is a language construct and not a function, it cannot be called using variable functions
empty
28-Nov-2008 01:54
27-Oct-2008 07:52
By definition empty( mixed* $var ) cannot accept all types. For example, define constants will cause error if you try to test them.
* mixed indicates that a parameter may accept multiple (but not necessarily all) types.
This will produce error:
define("CONSTANT", "Hello world.");
var_dump( empty( CONSTANT ) );
At first, this seemed to me very legal, but then I realized the fact that it just doesn't work.
26-Aug-2008 02:11
to john_jian,
for the loose equal operator(==), if both operands are not of the same data type, one of the operand will be converted to have the same data type as the other,
'' == 0 is true because '' is casted to integer 0,
0 == '0' is true because '0' is casted to integer 0,
'' == '0' is false because '' string is not equal to '0' string
22-Aug-2008 05:09
@john_jian, et al
PHP does have explicit type casting.
Also consider that, due to the implicit casting that Anonymous pointed out, "-" == (int)"-" and "+" == (int)"-" both evaluate as bool(true).
var_dump("-" == (int)"-");
var_dump("+" == (int)"-");
This is small hiccup that I ran into a few weeks back when validating some user input. I thought it was a bug at first, but it's not, it's just one of those gotchas that crop up sometimes when dealing with a typeless language.
It would be preferable, however, if PHP could raise an E_NOTICE when it encounters a cast that results in a default value such as in the above case.
22-Aug-2008 04:59
How about this improvement to Karl Jung's my_empty
<?php
function my_empty($val) {
$val = trim($val);
return empty($val) && $val !== 0;
}
?>
20-Aug-2008 02:41
To add on to what anon said, what's happening in john_jian's example seems unusual because we don't see the implicit typecasting going on behind the scenes. What's really happening is:
$a = '';
$b = 0;
$c = '0';
(int)$a == $b -> true, because any string that's not a number gets converted to 0
$b==(int)$c -> true, because the int in the string gets converted
and
$a==$c -> false, because they're being compared as strings, rather than integers. (int)$a==(int)$c should return true, however.
Note: I don't remember if PHP even *has* typecasting, much less if this is the correct syntax. I'm just using something for the sake of examples.
22-May-2008 05:01
In reply to "admin at ninthcircuit dot info",
Using str_replace is unnecessary. I would encourage the use of trim which would most likely be faster (haven't tested) and easier. Trim also takes care of other white space like line breaks and tabs. Actually, in most of the applications I code, I use a multi-dimensional array map function with trim on the Super Globals such as $_POST, $_GET and $_COOKIE as so far, there hasn't been an instance where I would want any user input to begin or end with whitespace. The good thing about doing this is that you never have to worry about 'trimming' your input which makes your code easier and more reliable (incase you forget to trim some input).
02-May-2008 02:55
David from CodeXplorer:
>> The ONLY reason to use empty() is for code readability. It is the same as an IF/ELSE check.
>> So, don't bother using EMPTY in the real world.
This is NOT true. empty() will not generate warnings if you're testing against an undefined variable as a simple boolean check will. On production systems, warnings are usually shut off, but they are often active on development systems.
You could test a flag with
<?php if ($flagvar) ... ?>
but this can generate a warning if $flagvar is not set.
Instead of
<?php if (isset($flagvar) && $flagvar) ... ?>
you can simply use
<?php if (!empty($flagvar)) ... ?>
for easy readability without warnings.
10-Mar-2008 09:29
Mad Hampster did his test wrong. empty is NOT faster than a simple boolean check. The ONLY reason to use empty() is for code readability. It is the same as an IF/ELSE check. But if you are dealing with intermediate or higher level coders this function has no other benefit.
So, don't bother using EMPTY in the real world.
I ran an array with 5000 simple true/false values through four checks (both types twice) in case of any gain one type might have by going first. These are my results generated one one page request. (PHP5)
0.015328 Time EMPTY
0.014281 Time IF/ELSE
0.015239 Time EMPTY
0.013404 Time IF/ELSE
The page was accessed a couple times to reduce caching effects.
31-Jan-2008 07:34
In addiction to Ed comment:
http://uk.php.net/manual/en/function.empty.php#80106
if an instance variable is assigned with an empty value, i.e. false, empty returns true.
<?php
class TestEmpty{
protected $empty;
public function __construct(){
var_dump(empty($this->empty)); // true
$this->empty = false;
var_dump(empty($this->empty)); // true
}
}
new TestEmpty;
?>
I think this is an expected behaviour but at the same time the note about classes variables is too ambiguous.
''var $var; (a variable declared, but without a value in a class)''
Please change them into something like:
''var $var; (a variable undeclared or declared with an empty value in a class)''
28-Jan-2008 10:59
Also note, that if you have a URI that looks like this:
/page/index.php?query=
performing isset($_GET['query']) will return TRUE. as query is set, though null, in the QUERY.
To counteract this behavior, check isset($_GET['query']) and !empty($_GET['query']) as empty will detect the null value.
29-Dec-2007 12:08
Also, it doesn't appear to mention in the documentation, if a variable hasn't previously been declared, empty also returns true.
E.g.
var $bar;
empty( $bar ); // declared variable returns true.
empty( $foo ); // undeclared variable also returns true.
The closest the documentation comes to saying this is:
"var $var; (a variable declared, but without a value in a class)"
which isn't really the same, as the variable doesn't necessarily have to be declared first.
12-Dec-2007 07:33
SAME RESULT! But somehow using empty() function is faster for about 10-13%
<?php
$array[] = "";
$array[] = '';
$array[] = 0;
$array[] = "0";
$array[] = NULL;
$array[] = false;
$array[] = array();
$array[] = $var;
foreach($array as $value){
echo (!empty($value))? 'Not empty!' : 'Empty!';
echo '<br />'."\r\n";
}
echo '<br />'."\r\n";
foreach($array as $value){
echo ($value)? 'Not empty!' : 'Empty!';
echo '<br />'."\r\n";
}
?>
04-Oct-2007 02:48
Here's what I do for the zero issue issue:
if($val == '' && $val !== 0 && $val !== '0')
15-Sep-2007 06:55
There's a faster and easier to write method than (isset($a) && strlen($a)) -- isset($a{0}). It evaluates to false if $a is not set or if it has zero length (ie. it's first character is not set). My tests indicate that it's about 33% faster.
05-Sep-2007 03:57
Since I didn't like how empty() considers 0 and "0" to be empty (which can easily lead to bugs in your code), and since it doesn't deal with whitespace, i created the following function:
<?php
function check_not_empty($s, $include_whitespace = false)
{
if ($include_whitespace) {
// make it so strings containing white space are treated as empty too
$s = trim($s);
}
return (isset($s) && strlen($s)); // var is set and not an empty string ''
}
?>
Instead of saying if (!empty($var)) { // it's not empty } you can just say if (check_not_empty($var)) { // it's not empty }.
If you want strings that only contain whitespace (such as tabs or spaces) to be treated as empty then do: check_not_empty($var, 1)
If you want to check if a string IS empty then do: !check_not_empty($var).
So, whenever you want to check if a form field both exists and contains a value just do: if (check_not_empty($_POST['foo'], 1))
no need to do if (isset() && !empty()) anymore =]
11-Jun-2007 12:06
Since a few people here mentioned that empty will not work with magic-overloading ("__get($var)"):
empty(..) goes the same way as isset(..) do, to check if a property exists. Thus you have to override the magic-function __isset($var) to produce correct results for empty(..) in combination with a magic-overloaded property.
28-Feb-2006 12:06
Re: inerte is my gmail.com username's comment:
While that may be true, those two statements (empty($var), $var == '') are NOT the same. When programming for web interfaces, where a user may be submitting '0' as a valid field value, you should not be using empty().
<?php
$str = '0';
// outputs 'empty'
echo empty($str) ? 'empty' : 'not empty';
// outputs 'not empty'
echo $str == '' ? 'empty' : 'not empty';
?>
19-Aug-2005 03:14
When using empty() on an object variable that is provided by the __get function, empty() will always return true.
For example:
<?php
class foo {
public function __get($var) {
if ($var == "bar") {
return "bar";
}
}
}
$object_foo = new foo();
echo '$object_foo->bar is ' . $object_foo->bar;
if (empty($object_foo->bar)) {
echo '$object_foo->bar seems to be empty';
}
?>
produces the following output:
$object_foo->bar is bar
$object_foo->bar seems to be empty
01-Jul-2005 09:10
empty($var) will return TRUE if $var is empty (according to the definition of 'empty' above) AND if $var is not set.
I know that the statement in the "Return Values" section of the manual already says this in reverse:
"Returns FALSE if var has a non-empty and non-zero value."
but I was like "Why is this thing returning TRUE for unset variables???"... oh i see now... Its supposed to return TRUE for unset variables!!!
<?php
ini_set('error_reporting',E_ALL);
ini_set('display_errors','1');
empty($var);
?>
24-May-2005 10:14
Something to note when using empty():
empty() does not see a string variable with nothing but spaces in it as "empty" per se.
Why is this relevant in a PHP application? The answer is.. if you intend to use empty() as a means of input validation, then a little extra work is necessary to make sure that empty() evaluates input with a more favorable outcome.
Example:
<?php
$spaces = " ";
/* This will return false! */
if (empty($spaces))
print "This will never be true!";
else
print "Told you!";
?>
To make empty() behave the way you would expect it to, use str_replace().
<?php
$spaces = str_replace(" ",""," ");
/* This will return true! */
if (empty($spaces))
print "This will always be true!";
else
print "Told you!";
?>
This might seem trivial given the examples shown above; however, if one were to be storing this information in a mySQL database (or your preferred DB of choice), it might prove to be problematic for retrieval of it later on.
22-May-2004 10:09
Note the exceptions when it comes to decimal numbers:
<?php
$a = 0.00;
$b = '0.00';
echo (empty($a)? "empty": "not empty"); //result empty
echo (empty($b)? "empty": "not empty"); //result not empty
//BUT...
$c = intval($b);
echo (empty($c)? "empty": "not empty"); //result empty
?>
For those of you using MySQL, if you have a table with a column of decimal type, when you do a SELECT, your data will be returned as a string, so you'll need to do apply intval() before testing for empty.
e.g.
TABLE t has columns id MEDIUMINT and d DECIMAL(4,2)
and contains 1 row where id=1, d=0.00
<?php
$q = "SELECT * FROM t";
$res = mysql_query($q);
$row = mysql_fetch_assoc($res);
echo (empty($row['d'])? "empty": "not empty"); //result not empty
?>
