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.
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
02-May-2008 02:55
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.
10-Jan-2008 01:19
@anonymus below
would you please pay attention to the following note in the documentation of empty():
"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)). "
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 11:00
According to the PHP bug repository the following behavior of empty isn't a bug, it's "a feature."
If you use the __get function with an object and then test a property of that object with empty() you will ALWAYS get false. You don't even get the benefit of an error or warning like you do when you try something like
empty(someFunction());
So instead you find yourself with the wonderful fun of tracing program flow. Beware using empty with objects. Better yet, use this one line wrapper function
function isEmpty($value) { return empty($value) }
This dodges the stupidity of the current implementation of empty() entirely. If you try to evaluate a property of an object set by __get in any way it will work with this wrapper function.
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";
}
?>
18-Oct-2007 08:44
If you are writing a form handling script and just need to check whether a required field has been filled in, you can just use strlen() to check the field. It handles all the cases properly when you are only dealing with strings.
$x = "0";
echo strlen($x); // returns 1
$x = "";
echo strlen($x); // returns 0
unset $x
echo strlen($x); // returns 0
In other words, the check you need to make becomes:
if (strlen($email) == 0)
$error = "Please enter your email address";
or
if (strlen($_POST["email"]) == 0)
$error = "Please enter your email address";
Hopes this helps anyone just seeking a workaround for the annoying empty("0") anomaly.
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 =]
26-Jul-2007 04:30
Hello,
I made something better than fnbh at freemail dot hu in order to put more variables as an arg into the empty function (like isset, you can put every var you want to, if one is not set, then it returns false : the behaviour of this function will do the same, except that if one of the variables if empty, then it returns true). But, I made it the simpliest way, and also i'm usign the foreach structure, which is, i believe so, is better than the for structure for an array.
Here it comes :
<?php
function multi_empty(){
// -- If no parameters, then it is empty (just a matter of logic, nah ?).
if( func_num_args() == 0 ){
return true;
}
$args = func_get_args();
// -- Getting through all the arguments. If there's one which is empty, then we return true : there is no reason to continue... ;)
foreach($args as $arg){
if( empty($arg) ){
return true;
}
}
// -- Nothing was found empty ; then the result is false.
return false;
}
?>
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.
23-May-2007 12:20
RE: Arian's comments on
empty( $someClass->someMethod() )
causing Fatal error: Can't use method return value in write context in ...
As retardedly simple as it is, just do this:
function emptyReturn( $var )
{
return empty( $var );
}
and substitute emptyReturn() anywhere you would use empty() on a function call.
I'm telling myself there's some good reason it is this way, but I'm not believing me.
23-Mar-2007 06:32
The empty() function is not exactly useful.... it defines both "0" and 0 (the numerical version) as empty. That's not really true is it!
Consider a user updating a record and setting a value to 0. When the form is posted and empty() is used to check for empty values it will return true. If you are testing for a mandatory field this will fail... even though the field has a value.
The following checks if a field is "really" empty, and includes as many test cases as I could think of.
<?php
function isempty($var) {
if (((is_null($var) || rtrim($var) == "") && $var !== false) || (is_array($var) && empty($var))) {
echo "yes<br />";
} else {
echo "no<br />";
}
}
echo "1. unset variable - yes - ";
isempty($unset);
echo "2. empty string - yes - ";
$var = "";
isempty($var);
echo "3. zero string - no - ";
$var = "0";
isempty($var);
echo "4. zero number - no - ";
$var = 0;
isempty($var);
echo "5. null string - yes - ";
$var = null;
isempty($var);
echo "6. single space - yes - ";
$var = " ";
isempty($var);
echo "7. several space - yes - ";
$var = " ";
isempty($var);
echo "8. true - no - ";
$var = true;
isempty($var);
echo "9. false - no - ";
$var = false;
isempty($var);
echo "10. empty array - yes - ";
$var = array();
isempty($var);
?>
The output from this should be...
1. unset variable - yes - yes
2. empty string - yes - yes
3. zero string - no - no
4. zero number - no - no
5. null string - yes - yes
6. single space - yes - yes
7. several space - yes - yes
8. true - no - no
9. false - no - no
10. empty array - yes - yes
Regards,
M
Speed comparisons between empty($foo) versus !$foo are pointless; you're saving what, a couple dozen nanoseconds? If you care that much you'll have to benchmark every single new version of PHP in case changes affect the relative speeds of your various methods, and then recode if one method overtakes another. Now THAT is a waste of time.
Far more important is that your code says what you want it to mean.
Besides, when $foo is not set empty($foo) is >1400% faster than !$foo (and that's AFTER suppressing the notice message).
02-Feb-2007 07:35
Read the above note carefully: "Note: empty() only checks variables as anything else will result in a parse error."
Took me forever to google around and figure out this error was related to above lines:
[02-Feb-2007 09:38:09] PHP Fatal error:
Can't use function return value in write context in blah.php on line ##
So hopefully someone else googling the error text itself, will track back to this page.
It would be nice though if empty() can 'correctly' parse and return a value for a function call within itself like other funcs.
01-Feb-2007 12:39
In response to a previous post regarding the speed of:
if (empty($var))
versus
if (!$var)
or
if (!empty($var))
versus
if ($var)
In fact I found that the empty() function is always slower. I have tested this on three different machines; Celeron, Pentium M, and an AMD Athlon 64. These all run php 5.2, and I have repeated the tests a number of times using different loops and variable types. My results show that, on average, empty() takes around 15 - 20% longer to complete its task.
22-Jan-2007 02:08
I wanted to correct a couple of errors in some earlier user notes, regarding which is better, using empty() within an if clause to be evaluated, or using only the variable. E.g.:
if (!$blah)
versus
if (empty($blah))
or
if ($blah)
versus
if (!empty($blah))
First, one person noted that empty() is basically worthless because you don't need it to do the above functionality. However, I think this is wrong for 2 reasons:
1. It is needed for arrays and (I think) objects
2. empty() is actually FASTER than using just the variable. You might think that it would be slower because it looks like a function, but it is actually a language construct. Apparently it is optimized. It is at least 10% faster, sometimes nearly 20% faster.
Second, one person claimed that if you don't use empty, and just test the variable, you will get an E_WARNING error. I don't know if this used to be true, but for me in PHP 5.2, it only generates an E_NOTICE.
I hope this clears up somebody's confusion.
08-Jan-2007 03:13
for beginers:
function empty_vars() {
// if ((empty($var1)) || (empty($var2)) .... ) (lazy func)
if (func_num_args()==0) return true;
$vars=func_get_args();
for ($i = 0; $i < $vars; $i++) {
if (empty($vars[$i])) {
return true;
}
}
return false;
}
15-Nov-2006 07:14
The empty function will not work on an attribute of an object when the object uses the __get method.
The following code:
<?php
class Person {
protected $name_;
public function __construct($name) {
$this->name_ = $name;
}
public function __get($name) {
// just return name
return $this->name_;
}
}
class FirstPerson extends Person {
public function __construct() {
parent::__construct('The great cornholio');
}
public function __get($name) {
return parent::__get($name);
}
}
$tgc = new FirstPerson;
print 'Name: '.$tgc->name.'<br />';
if (!empty($tgc->name)) {
print 'Name via getter is not empty';
} else {
print 'Name via getter is empty';
}
?>
Results in:
Name: The great cornholio
Name via getter is empty
10-Jul-2006 07:45
The two following methods will do exactly the same, in any case:
<?php
// CASE 1
if ( empty($var) )
{
// do your thing
}
// CASE 2
if ( !isset($var) || !$var )
{
// do that same thing
}
?>
empty( ) checks for isset AND also the value of the variable (0, "0", "", etc).
03-Jun-2006 09:03
This function I did, works like empty(), but doesn't consider zero (0) as empty.
Also, considers as empty, a string containing only blank spaces, or "\n", "\t", etc.
function my_empty($val)
{
$result = false;
if (empty($val))
$result = true;
if (!$result && (trim($val) == ""))
$result = true;
if ($result && is_numeric($val) && $val == 0)
$result = false;
return $result;
}
Values considered as EMPTY:
$val = "";
$val = " ";
$val = " \t \n ";
$val = array();
$val = false;
$val = null;
Values considered NOT EMPTY:
$val = "0";
$val = intval(0);
$val = floatval(0);
28-Apr-2006 11:53
Followup to ben at wbtproductions dot com:
You'll want to do this check for numeric 0:
<?
if ($data === 0) echo 'The data is zero.';
?>
Checking $data == 0 basically means the same thing as "is $data false?". Loose type checking is a gotcha you should look out for.
18-Apr-2006 05:40
It is important to note that empty() does not check data type. This can change the functioning of any program if, at some point, your data might be all zeroes, containing no real data, but also not empty by PHP's definition.
Think about this:
$data = "00000";
if (empty($data))
echo "The data appears empty.";
if (0==$data) //Use this test for number applications!!
echo "The data is zero.";
$data = 0;
if (empty($data))
echo "Remember, zero is empty.";
outputs:
The data is zero.
Remember, zero is empty.
This could crop up in ZIP codes and phone numbers or zero-filled/zero-padded values from SQL. Watch those variable types!
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';
?>
31-Jan-2006 09:35
But not faster than
if (!$var)
{
}
which is about 20% faster than empty() on php5.1
11-Nov-2005 06:58
empty() is about 10% faster than a comparision.
if (empty($var)) {
}
is faster than:
if ($var == '') {
}
YMMV, empty() also checks array and attributes, plus 0, and '' is kind a string with nothing inside. But I was using '' and got a huge performance boost with empty().
PHP 4.3.10-15, Apache/2.0.54, Kernel 2.4.27-2-386.
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:
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);
?>
30-Jun-2005 08:02
I needed to know if the variable was empty, but allow for it to be zero, so I created this function. I post it here in case anybody else needs to do that (it's not hard to make, but why reinvent the wheel...)
<?php
function is_extant($var)
{
if (isset($var))
{
if ( empty($var) && ($var !== 0) && ($var !== '0') )
return FALSE;
else
return TRUE;
}
else
return FALSE;
}
?>
09-Jun-2005 08:43
admin at prelogic dot net has wrote the following
In response to admin at ninthcircuit dot info
The best way around that is the trim function. For example:
$spaces = " ";
if(empty(trim($spaces)){
echo "Omg empty string.";
}else{
echo "Omg the string isnt empty!";
}
Hope that helps anyone, though it is rather trivial.
i think is said above that empty(trim($spaces)) dont work
,i think is better to seperate this two function
trim($spaces);
empty($spaces) thern continue with the code......
08-Jun-2005 06:45
In response to "admin at ninthcircuit dot info" :
Instead of using "$spaces = str_replace(" ",""," ");"
you should use the function "trim()", which clear spaces before and after the string. e.g. "trim(' example 1 ')" returns "example 1".
27-May-2005 04:17
In Response to Zigbigidorlu:
Using if (!$_POST['foo']) is not the best way to test if a variable is empty/set. Doing that creates a E_WARNING error for an uninitialized variable, and if you are planning to use a rather high error level, this is not the better way, since this will create an error whereas if (!isset($_POST['foo'])) or (empty($_POST['foo'])) doesn't echo an error, just returns true/false appropriately.
One example of this is in the phpBB code - the coding guidelines state that you have to use isset() or empty() to see if a variable is set, since they planned to use a higher level of error reporting.
24-May-2005 10:44
This function is of very little use, as the "!" operator creates the same effect.
<?
if(empty($_POST['username']) exit;
?>
has the exact same functionality as:
<?
if(!$_POST['username']) exit;
?>
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.
24-May-2005 10:13
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.
29-Apr-2005 08:15
<?php
$a = Array( ); #<- empty
$a = Array( '' ); #<- NOT empty
$a = Array( Null ); #<- NOT empty
?>
---
gabriel
23-Aug-2004 01:47
ive found the empty() contruct extremely usefull. For some reason people seem to think its of little use, but thats not so.
for example, form fields can be checked in 1 step by using empty(). (assuming a basic check of whether it was submitted and if submitted, that it was not empty.)
<?php
if (!empty($_POST['name'])) $name = $_POST['name'];
?>
compared to isSet(), this saves an extra step. using !empty() will check if the variable is not empty, and if the variable doesnt exit, no warning is generated.
with isSet(), to acheive the same result as the snippit above, you would need to do this:
<?php
if (isSet($_POST['name']) && $_POST['name']) $name = $_POST['name'];
?>
so using !empty() reduces code clutter and improves readability, which IMO, makes this VERY usefull.
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
?>
26-Nov-2002 11:18
the php cheatsheet gives a good overview for empty(), isSet(), is_null() etc. http://www.blueshoes.org/en/developer/php_cheat_sheet/
to chris at chaska dot com:
that line
if ( ! isset( $var ) ) return TRUE;
won't do anything, it's useless in that scope.
