dismiss Step into the future! Click here to switch to the beta php.net site
downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

floatval> <doubleval
[edit] Last updated: Fri, 23 Aug 2013

view this page in

empty

(PHP 4, PHP 5)

emptyПроверяет, пуста ли переменная

Описание

bool empty ( mixed $var )

Проверяет, пуста ли переменная.

Список параметров

var

Проверяемая переменная

Замечание:

empty() проверяет только переменные, и попытка проверить что-то еще вызовет ошибку синтаксиса. Другими словами, следующий код не будет работать: empty(trim($name)).

empty() является противоположностью (boolean) var, за исключением того, что в случае неопределенной переменной не будет сгенерировано предупреждения.

Возвращаемые значения

Возвращает FALSE, если var содержит непустое и ненулевое значение.

Следующие значения воспринимаются как пустые:

  • "" (пустая строка)
  • 0 (целое число)
  • 0.0 (дробное число)
  • "0" (строка)
  • NULL
  • FALSE
  • array() (пустой массив)
  • var $var; (переменная объявлена, но не имеет значения в классе)

Список изменений

Версия Описание
5.4.0

Проверка нечислового индекса строки возвращает TRUE.

5.0.0

Объекты без свойств более не считаются пустыми.

Примеры

Пример #1 Простое сравнение empty() и isset().

<?php
$var 
0;

// Принимает значение true, потому что $var пусто
if (empty($var)) {
    echo 
'$var или 0, или пусто, или вообще не определена';
}

// Принимает значение true, потому что $var определена
if (isset($var)) {
    echo 
'$var определена, даже если она пустая';
}
?>

Пример #2 empty() и строковые индексы

В PHP 5.4 был изменен способ обработки строковых индексов в empty().

<?php
$expected_array_got_string 
'somestring';
var_dump(empty($expected_array_got_string['some_key']));
var_dump(empty($expected_array_got_string[0]));
var_dump(empty($expected_array_got_string['0']));
var_dump(empty($expected_array_got_string[0.5]));
var_dump(empty($expected_array_got_string['0.5']));
var_dump(empty($expected_array_got_string['0 Mostel']));
?>

Результат выполнения данного примера в PHP 5.3:

bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)

Результат выполнения данного примера в PHP 5.4:

bool(true)
bool(false)
bool(false)
bool(false)
bool(true)
bool(true)

Примечания

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.

Замечание:

При использовании функции empty() на недоступных (необъявленных) свойствах объекта будет вызван встроенный метод объекта __isset(), если он определен.

Смотрите также

  • isset() - Определяет, была ли установлена переменная значением отличным от NULL
  • __isset()
  • unset() - Удаляет переменную
  • array_key_exists() - Проверяет, присутствует ли в массиве указанный ключ или индекс
  • count() - Подсчитывает количество элементов массива или что-то в объекте
  • strlen() - Возвращает длину строки
  • Таблица сравнения типов



floatval> <doubleval
[edit] Last updated: Fri, 23 Aug 2013
 
add a note add a note User Contributed Notes empty - [39 notes]
up
down
8
rodolphe dot bodeau at free dot fr
2 years ago
Be careful, if "0" (zero as a string), 0 (zero as an integer) and -0 (minus zero as an integer) return true, "-0" (minus zero as a string (yes, I already had some customers that wrote -0 into a form field)) returns false. You need to cast your variable before testing it with the empty() function :

<?php
$var
= "-0";
echo empty(
$var);  // returns false
$var = (int) $var; // casts $var as an integer
echo empty($vat);  // returns true
?>
up
down
5
chris dot wisefool at gmail dot com
1 year ago
Note that checking the existence of a subkey of an array when that subkey does not exist but the parent does and is a string will return false for empty.

i.e.

<?php
$params
= array('search'=>'1');
empty(
$params['search']['filter']); # returns false
?>

This is correct, per the documentation (http://php.net/manual/en/language.types.string.php); quite a bit down the page is the Warning: "Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer." ) I didn't receive a warning but perhaps that's correct too...depends on whether the string -> integer conversion is considered "illegal": "Illegal offset type emits E_NOTICE."

(i.e. since $params['search'] is a string, the 'filter' subscript is converted to 0, so the test becomes empty($params['search'][0]), which is obviously false), but it tripped me up enough to mistakenly file a bug report (which I've since closed).
up
down
7
denobasis-bozic et yahoo.com
4 years ago
test if all multiarray's are empty

<?php
function is_multiArrayEmpty($multiarray) {
    if(
is_array($multiarray) and !empty($multiarray)){
       
$tmp = array_shift($multiarray);
            if(!
is_multiArrayEmpty($multiarray) or !is_multiArrayEmpty($tmp)){
                return
false;
            }
            return
true;
    }
    if(empty(
$multiarray)){
        return
true;
    }
    return
false;
}

$testCase = array (    
0 => '',
1 => "",
2 => null,
3 => array(),
4 => array(array()),
5 => array(array(array(array(array())))),
6 => array(array(), array(), array(), array(), array()),
7 => array(array(array(), array()), array(array(array(array(array(array(), array())))))),
8 => array(null),
9 => 'not empty',
10 => "not empty",
11 => array(array("not empty")),
12 => array(array(),array("not empty"),array(array()))
);

foreach (
$testCase as $key => $case ) {
    echo
"$key is_multiArrayEmpty= ".is_multiArrayEmpty($case)."<br>";
}
?>

OUTPUT:
========

0 is_multiArrayEmpty= 1
1 is_multiArrayEmpty= 1
2 is_multiArrayEmpty= 1
3 is_multiArrayEmpty= 1
4 is_multiArrayEmpty= 1
5 is_multiArrayEmpty= 1
6 is_multiArrayEmpty= 1
7 is_multiArrayEmpty= 1
8 is_multiArrayEmpty= 1
9 is_multiArrayEmpty=
10 is_multiArrayEmpty=
11 is_multiArrayEmpty=
12 is_multiArrayEmpty=
up
down
4
martin dot aarhof at gmail dot com
1 year ago
<?php
$str
= '            ';
var_dump(empty($str)); // boolean false
?>

So remember to trim your strings first!

<?php
$str
= '        ';
$str = trim($str);
var_dump(empty($str)); // boolean true
?>
up
down
4
e dot klerks at i-bytes dot nl
2 years ago
To make an empty function, which only accepts arrays, one can use type-hinting:

<?php
// emptyArray :: [a] -> Bool

function emptyArray(array $xs){
 return empty(
$xs);
}
?>

Type hinting is a good thing to use in your code, because it makes it more easy to reason about your code. Besides that, it automatically documents the code.
up
down
4
EllisGL
5 years ago
Here's what I do for the zero issue issue:
if($val == '' && $val !== 0 && $val !== '0')
up
down
7
steven at nevvix dot com
2 years ago
When you need to accept these as valid, non-empty values:
- 0 (0 as an integer)
- 0.0 (0 as a float)
- "0" (0 as a string)

<?php
function is_blank($value) {
    return empty(
$value) && !is_numeric($value);
}
?>

This is similar to Rails' blank? method.
up
down
4
phpsort
2 years ago
I'm summarising a few points on empty() with inaccessible properties, in the hope of saving others a bit of time. Using PHP 5.3.2.
<?php
class MyClass {
    private
$foo = 'foo';
}
$myClass = new MyClass;
echo
$myClass->foo;
?>
As expected, this gives "Fatal error: Cannot access private property MyClass::$foo".
But substitute the line
if (empty($myClass->foo)) echo 'foo is empty'; else echo 'foo is not empty';
and we get the misleading result "foo is empty".
There is NO ERROR OR WARNING, so this is a real gotcha. Your code will just go wrong silently, and I would say it amounts to a bug.
If you add two magic functions to the class:
public function __get($var) { return $this->$var; }
public function __isset($var) { return isset($this->$var); }
then we get the expected result. You need both functions.
For empty($myClass->foo), I believe PHP calls __isset, and if that is true returns the result of empty on the result of __get. (Some earlier posts wrongly suggest PHP just returns the negation of __isset).
BUT …
See the earlier post by php at lanar dot com. I confirm those results, and if you extend the test with isset($x->a->b->c) it appears that __isset is only called for the last property in the chain. Arguably another bug. empty() behaves in the same way. So things are not as clear as we might hope.
See also the note on empty() at
http://uk3.php.net/manual/en/language.oop5.overloading.php
Clear as mud!
up
down
2
tom at tomwardrop dot com
5 years ago
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).
up
down
2
marko dot crni at gmail dot com
2 years ago
Calling non existing object property, empty($object->prop), will trigger __isset(), the same way as isset($object->prop) does, but there is one difference. If __isset() returns TRUE, another call to __get() will be made and actual return value will be result of empty() and result of __get().
up
down
1
jmarbas at hotmail dot com
8 years ago
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);
?>
up
down
1
qeremy
1 year ago
Simple solution for: "Fatal error: Can't use function return value in write context in ..."

<?php
function _empty($val) { return empty($val); }
?>
up
down
1
ehsmeng
2 years ago
I can't use empty() in all situations because '0' is usually not considered empty to me. I did a quick benchmark over the most common ways of testing it. '' == var suffers from '' == 0 is true so that's just there for curiosity.

<?php
    $microtimeref
= microtime(true);
   
$a = 0;
   
$b = 'asd';
    for (
$i = 0; $i < 5000000; $i++)
    {
        if (
0 == mb_strlen ($b))
        {
           
$a++;
        }
    }
    echo
"Total time 0 == mb_strlen(var): <b>" . round(microtime(true) - $microtimeref,3) . 's</b><br />';
?>

The results:

Total time 0 == mb_strlen(var): 3.141s
Total time 0 === strlen(var): 2.904s
Total time 0 == strlen(var): 2.878s
Total time '' == var: 1.774s
Total time '' === var: 1.706s
Total time empty(var): 1.496s

Thus '' === var will be my zero length string test.
up
down
0
serkons at yahoo dot com
2 years ago
Hi you can check the status of multiple array or any variable is empty with below code.

<?php
$microtimeref
= microtime ( true );
//$variable=null; // false,true,0,''
//$variable = array ('id' => 10, 'name' => 'serkon' );
$variable = array (array (0) );
echo
'<pre>';
function
getArray($dizi) {
    foreach (
$dizi as $value )
        return
$value;
}
function
isEmpty($array) {
    if (
is_array ( $array )) {
       
$dizi = getArray ( $array );
        if (
is_array ( $dizi ))
           
$ref = isEmpty ( $dizi );
        else
            if (
strlen ( $dizi ) >= 1)
                return
false;
            else
                return
true;
    }
    else
        if (
strlen ( $array ) >= 1)
            return
false;
        else
            return
true;
   
    if (
$ref === false)
        return
false;
    else
        return
true;
}
$sonuc = isEmpty ( $variable );
var_dump ( $sonuc );
echo
"Total time: <b>" . round ( microtime ( true ) - $microtimeref, 4 ) . 's</b><br />';
echo
'</pre>';
?>

Response:

bool(false)  // not empty
Total time: 0s
up
down
0
Janci
4 years ago
Please note that results of empty() when called on non-existing / non-public variables of a class are a bit confusing if using magic method __get (as previously mentioned by nahpeps at gmx dot de). Consider this example:

<?php
class Registry
{
    protected
$_items = array();
    public function
__set($key, $value)
    {
       
$this->_items[$key] = $value;
    }
    public function
__get($key)
    {
        if (isset(
$this->_items[$key])) {
            return
$this->_items[$key];
        } else {
            return
null;
        }
    }
}

$registry = new Registry();
$registry->empty = '';
$registry->notEmpty = 'not empty';

var_dump(empty($registry->notExisting)); // true, so far so good
var_dump(empty($registry->empty)); // true, so far so good
var_dump(empty($registry->notEmpty)); // true, .. say what?
$tmp = $registry->notEmpty;
var_dump(empty($tmp)); // false as expected
?>

The result for empty($registry->notEmpty) is a bit unexpeced as the value is obviously set and non-empty. This is due to the fact that the empty() function uses __isset() magic functin in these cases. Although it's noted in the documentation above, I think it's worth mentioning in more detail as the behaviour is not straightforward. In order to achieve desired (expexted?) results, you need to add  __isset() magic function to your class:

<?php
class Registry
{
    protected
$_items = array();
    public function
__set($key, $value)
    {
       
$this->_items[$key] = $value;
    }
    public function
__get($key)
    {
        if (isset(
$this->_items[$key])) {
            return
$this->_items[$key];
        } else {
            return
null;
        }
    }
    public function
__isset($key)
    {
        if (isset(
$this->_items[$key])) {
            return (
false === empty($this->_items[$key]));
        } else {
            return
null;
        }
    }
}

$registry = new Registry();
$registry->empty = '';
$registry->notEmpty = 'not empty';

var_dump(empty($registry->notExisting)); // true, so far so good
var_dump(empty($registry->empty)); // true, so far so good
var_dump(empty($registry->notEmpty)); // false, finally!
?>

It actually seems that empty() is returning negation of the __isset() magic function result, hence the negation of the empty() result in the __isset() function above.
up
down
0
emperoruk at dontspam dot hotmail dot com
4 years ago
When using the php empty() function to check submitted variables such as $_POST or $_GET, be careful to remember that values 0 (integer) and "0" (string with zero character) are all considered empty. eg. in a simple cms a page ID of zero might be used to indicate that the homepage should be displayed but using the following code:

<?php
if (isset($_GET['pid'] && !empty($_GET['pid']) {
 
// assign value to local variable
 
$pageID = $_GET['pid'];
} else {
  echo
"missing variable 'pageID'";
}
?>

When attempting to display the homepage using a pid of zero the above code will fail.

So as a result i wrote a small function to replace the php empty() function in situations where you want 0 and "0" not to be considered empty.

<?php
function is_empty($var, $allow_false = false, $allow_ws = false) {
    if (!isset(
$var) || is_null($var) || ($allow_ws == false && trim($var) == "" && !is_bool($var)) || ($allow_false === false && is_bool($var) && $var === false) || (is_array($var) && empty($var))) {   
        return
true;
    } else {
        return
false;
    }
}
?>

This function will allow you to test a variable is empty and considers the following values as empty:

an unset variable -> empty
null -> empty
0 -> NOT empty
"0" -> NOT empty
false -> empty
true -> NOT empty
'string value' -> NOT empty
"    " (white space) -> empty
array() (empty array) -> empty

There are two optional parameters:

$allow_false: setting this to true will make the function consider a boolean value of false as NOT empty. This parameter is false by default.

$allow_ws: setting this to true will make the function consider a string with nothing but white space as NOT empty. This parameter is false by default.

In Testing:

<?php
// an unset variable
echo 'unset variable ($notset) - Empty: ';
echo
is_empty($notset) ? 'yes<br />' : 'no<br />';
// NULL variable
echo 'null - Empty: ';
$var = null;
echo
is_empty($var) ? 'yes<br />' : 'no<br />';
// integer 0
echo '0 - Empty: ';
$var = 0;
echo
is_empty($var) ? 'yes<br />' : 'no<br />';
// string "0"
echo 'string "0" - Empty: ';
$var = "0";
echo
is_empty($var) ? 'yes<br />' : 'no<br />';
// boolean value false
echo 'false - Empty: ';
$var = false;
echo
is_empty($var) ? 'yes<br />' : 'no<br />';
// allow boolean value false
echo 'false ($allow_false = true) - Empty: ';
$var = false;
echo
is_empty($var, true) ? 'yes<br />' : 'no<br />';
// boolean value true
echo 'true - Empty: ';
$var = true;
echo
is_empty($var) ? 'yes<br />' : 'no<br />';
// string
echo 'string "foo" - Empty: ';
$var = "foo";
echo
is_empty($var) ? 'yes<br />' : 'no<br />';
// white space
echo 'white space "     " - Empty: ';
$var = "    ";
echo
is_empty($var) ? 'yes<br />' : 'no<br />';
// allow white space
echo 'white space ($allow_ws = true) "     " - Empty: ';
$var = "    ";
echo
is_empty($var, false, true) ? 'yes<br />' : 'no<br />';
// empty array
echo 'empty array - Empty: ';
$var = array();
echo
is_empty($var) ? 'yes<br />' : 'no<br />';
?>

the above code outputs the following:

unset variable ($notset) - Empty: yes
null - Empty: yes
0 - Empty: no
string "0" - Empty: no
false - Empty: yes
false ($allow_false = true) - Empty: no
true - Empty: no
string "foo" - Empty: no
white space " " - Empty: yes
white space ($allow_ws = true) " " - Empty: no
empty array - Empty: yes

Hope this code is useful for someone.

Michael
up
down
0
thomas at thomasnoest dot nl
4 years ago
Note on the selfmade empty function below:

function_exists() returns false on language constructs and empty is a language construct.
up
down
0
Anonymous
5 years ago
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.
up
down
0
David from CodeXplorer
5 years ago
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.
up
down
0
jay at w3prodigy dot com
5 years ago
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.
up
down
0
Ed
5 years ago
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.
up
down
0
Antone Roundy
5 years ago
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.
up
down
0
rkulla2 at gmail dot com
5 years ago
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 =]
up
down
0
florian.sonner [at] t-online.de
6 years ago
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.
up
down
0
paul at worldwithoutwalls dot co dot uk
9 years ago
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
?>
up
down
-1
aidan1103 at yahoo dot com
3 years ago
empty() should not necessarily return the negation of the __isset() magic function result, if you set a data member to 0, isset() should return true and empty should also return true.  A simpler implementation of the __isset magic function would be:

public function __isset($key) {
  return isset($this->{$key});
}

I don't understand why this isn't included in stdClass and inherited by default.
up
down
-2
Andrea Giammarchi
5 years ago
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)''
up
down
-3
nahpeps at gmx dot de
8 years ago
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
up
down
-2
christian dot achatz at adventure-php-framework dot org
2 years ago
Since this special case is not mentioned already: the empty() check does not work for mysqli resources / connections stored within a private variable.

Instead of

if(!empty($this->dbConn->error)){...}

you have to use

$error = $this->dbConn->error;
if(!empty($error)){...}

otherwise the condition will not evaluate to true in case a mysqli error is given for the present connection.
up
down
-2
mlibazisi mabandla
4 years ago
in cases when "0" is not intended to be empty, here is a simple function to safely test for an empty string (or mixed variable):

<?php
function _empty($string){
    
$string = trim($string);
     if(!
is_numeric($string)) return empty($string);
     return
FALSE;
}
?>
up
down
-2
contato at andersonfraga dot net
4 years ago
<?php

function _empty() {
    foreach(
func_get_args() as $args) {
        if( !
is_numeric($args) ) {
            if(
is_array($args) ) { // Is array?
               
if( count($args, 1) < 1 ) return true;
            }
            elseif(!isset(
$args) || strlen(trim($args)) == 0)
                return
true;
            }
        }
    }
    return
false;
}

?>
up
down
-2
nobody at example dot com
7 years ago
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';
?>
up
down
-4
MaD HamsteR
5 years ago
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";
}

?>
up
down
-2
admin at ninthcircuit dot info
8 years ago
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.
up
down
-5
php at sethsyberg dot com
3 years ago
To find if an array has nothing but empty (string) values:

<?php
$foo
= array('foo'=>'', 'bar'=>'');
$bar = implode('', $foo);

if (empty(
$bar)) {
    echo
"EMPTY!";
} else {
    echo
"NOT EMPTY!";
}
?>
up
down
-5
justin at booleangate dot org
5 years ago
How about this improvement to Karl Jung's my_empty

<?php
function my_empty($val) {
   
$val = trim($val);
  
    return empty(
$val) && $val !== 0;
}
?>
up
down
-4
Greg Hartwig
5 years ago
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.
up
down
-3
kleingeist
3 years ago
Another, simpler, implementation to test if mulitarrays are empty.

<?php
function array_empty($mixed) {
    if (
is_array($mixed)) {
        foreach (
$mixed as $value) {
            if (!
array_empty($value)) {
                return
false;
            }
        }
    }
    elseif (!empty(
$mixed)) {
        return
false;
    }
    return
true;
}
?>
up
down
-4
nizamgok at gmail dot com
4 years ago
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.
add a note add a note

 
show source | credits | stats | sitemap | contact | advertising | mirror sites