php教程

empty

(PHP 4, PHP 5, PHP 7)

empty检查一个变量是否为空

说明

empty ( mixed $var ) : bool

判断一个变量是否被认为是空的。当一个变量并不存在,或者它的值等同于FALSE,那么它会被认为不存在。如果变量不存在的话,empty()并不会产生警告。

参数

var

待检查的变量

Note:

在 PHP 5.5 之前,empty() 仅支持变量;任何其他东西将会导致一个解析错误。换言之,下列代码不会生效: empty(trim($name))。 作为替代,应该使用trim($name) == false.

没有警告会产生,哪怕变量并不存在。 这意味着 empty() 本质上与 !isset($var) || $var == false 等价。

返回值

var存在,并且是一个非空非零的值时返回 FALSE 否则返回 TRUE.

以下的东西被认为是空的:

  • "" (空字符串)
  • 0 (作为整数的0)
  • 0.0 (作为浮点数的0)
  • "0" (作为字符串的0)
  • NULL
  • FALSE
  • array() (一个空数组)
  • $var; (一个声明了,但是没有值的变量)

更新日志

版本 说明
5.5.0

empty() 现在支持表达式了,而不仅仅是变量。

5.4.0

检查非数字的字符串偏移量会返回 TRUE.

范例

Example #1 一个简单的 empty()isset() 的比较。

<?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';
}
?>

Example #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)

注释

Note: 因为是一个语言构造器而不是一个函数,不能被 可变函数 调用。

Note:

当对一个不可见的对象属性使用 empty() 时, __isset() 方法如果存在的话,它将会被调用。

参见

User Contributed Notes

markmanning at gmail dot com 23-Mar-2019 09:15
I normally count() an array, so I wanted to see how empty() would stack up.

<?php
    $test
= array();
   
$test2 = array();
    for (
$x = 0; $x < 1000; $x++)  $test[] = $x;

   
$ts = microtime(true);
    for (
$x = 0; $x < 100000000; $x++)
    {
        if (
count($test))
        {
        }
    }

    echo
"Time taken:  " . (microtime(true) - $ts) . " sec\n";
?>

For 100,000,000 comparisons, here are the results against PHP 7.2.16 on my hardware:

count($test):  2.697 sec
count($test2):  2.596 sec
$test === array():  2.579 sec
$test2 === array():  2.552 sec
empty($test):  3.085 sec
empty($test2):  3.113 sec

In short, it doesn't matter what method is used although empty() is actually just ever so slightly slower despite it being a language construct.  YMMV.
fahimcseiiuc at gmail dot com 25-Feb-2019 10:02
<?php

   
/*"" (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)*/

$anEmptyString = "";
empty(
$anEmptyString);
if(empty(
$anEmptyString) == TRUE){
    echo
"TRUE";
} else{
    echo
"FALSE";
}
echo
"<hr>";         //line break

$anIntegerNumber = 0;
empty(
$anIntegerNumber);
if(empty(
$anIntegerNumber) == TRUE){
    echo
"TRUE";
} else{
    echo
"FALSE";
}
echo
"<hr>";         //line break

$aFloatNumber = 0.0;
empty(
$aFloatNumber);
if(empty(
$aFloatNumber) == TRUE){
    echo
"TRUE";
} else{
    echo
"FALSE";
}
echo
"<hr>";       //line break

$aZeroValuedString = "0";
empty(
$aZeroValuedString);
if(empty(
$aZeroValuedString) == TRUE){
    echo
"TRUE";
} else{
    echo
"FALSE";
}
echo
"<hr>";        //line break

$aNULL = NULL;
empty(
$aNULL);
if(empty(
$aNULL) == TRUE){
    echo
"TRUE";
} else{
    echo
"FALSE";
}
echo
"<hr>";        //line break

$aBooleanFALSE = FALSE;
empty(
$aBooleanFALSE);
if(empty(
$aBooleanFALSE) == TRUE){
    echo
"TRUE";
} else{
    echo
"FALSE";
}
echo
"<hr>";        //line break

$anEmptyArray = array();
empty(
$anEmptyArray);
if(empty(
$anEmptyArray) == TRUE){
    echo
"TRUE";
} else{
    echo
"FALSE";
}
echo
"<hr>";       //line break

?>
GazetteSDF 21-Sep-2018 09:02
For the verification of a form, to "block" entries such as a simple space or other, I thought of this combination:

function isEmpty($string){
    $val = preg_replace('#[^A-Za-z0-9]+#', '', $string) ;
    $val = trim($string, '');
    return ($string=='') ;
}

This protects entries like: ' ' ,'  -  ', '. - +', ... On entries like name, profession, ... it's helpful
DimeCadmium 14-Sep-2018 07:34
Each of the following statements is equivalent:

<?php
empty($x)
(!isset(
$x) || !$x)
!(isset(
$x) && $x)
?>

Note that this means PHP's odd and painful understanding of falsey is used, implying that you can not use empty() to, say, determine if a form has been filled out fully. (Or you'll have fun when someone wants to put "0" in a field.)
bert at elicom dot nl 09-Mar-2018 01:02
Never EVER use the empty() function.

There are good alternatives (e.g. explicitly checking against '', 0, and '0'), and since PHP variable types are determined by context, it will be unclear what a particular empty() is doing in your code. Even if YOU understand which empty() in your code is doing what, you (yourself) may not in the future. Or someone else may one day be studying/using/building upon your code, and this other person may not even know about the misleading behavior of empty(). So, even if YOU know exactly where to use and not use empty(), and what exactly it will do for you, help your fellow coders by never using it.
aditycse at gmail dot com 10-Nov-2017 03:58
<?php

/**
 * Used for checking empty objects/array
 * @uses How to check empty objects and array in php code
 * @author Aditya Mehrotra<aditycse@gmail.com>
 */

/**
 * Empty class
 */
class EmptyClass {
   
}

$obj = new stdClass();
//or any other class empty object
$emptyClassObj = new EmptyClass();
$array = array();

if (empty(
$array)) {
    echo
'array is empty'; //expected result
} else {
    echo
'array is not empty'; //unexpected result
}
echo
"<br>";

if (empty(
$obj)) {
    echo
'object is empty'; //expected result
} else {
    echo
'object is not empty'; //unexpected result
}
echo
"<br>";

if (empty(
$emptyClassObj)) {
    echo
'EmptyClass is empty'; //expected result
} else {
    echo
'EmptyClass is not empty'; //unexpected result
}
echo
"<br>";

//Result SET 1
//array is empty      => expected result
//object is not empty => ouch what happened
//EmptyClass is not empty => ouch what happened

/**
 * So what we do for checking empty object
 * @solution use any known property or check property count
 * Or you can use below method
 * Count function will not return 0 in empty object
 */

//Below line print "Object count:1"
echo 'Object count:' . count($obj);

echo
"<br>";

/**
 * This function is used to get object item counts
 * @function getCount
 * @access public
 * @param object|array $var
 * @return integer
 */
function getCount($var) {
   
$count = 0;
    if (
is_array($var) || is_object($var)) {
        foreach (
$var as $value) {
           
$count++;
        }
    }
    unset(
$value);
    return
$count;
}

//Running code again with new logic
if (getCount($array) === 0) {
    echo
'array is empty'; //expected result
} else {
    echo
'array is not empty'; //unexpected result
}
echo
"<br>";

if (
getCount($obj) === 0) {
    echo
'object is empty'; //expected result
} else {
    echo
'object is not empty'; //unexpected result
}

echo
"<br>";

if (
getCount($emptyClassObj) === 0) {
    echo
'EmptyClass is empty'; //expected result
} else {
    echo
'EmptyClass is not empty'; //unexpected result
}

//Result SET 2
//array is empty    => expected result  ##everything is all right
//object is empty   => expected result  ##everything is all right
//EmptyClass is empty   => expected result  ##everything is all right
xzero at elite7hackers dot net 13-Jul-2017 11:36
Note that empty() will return false on null byte. Eg.

<?php
// Save to variable, so it works on older PHP versions
$null_byte = chr(0); // === \0

var_dump(
    empty(
null),
    empty(
$null_byte)
);
/**
 * Results:
 *
 * bool(true)
 * bool(false)
 */
wranvaud at gmail dot com 02-Jul-2017 06:22
Note that if your variable only has an "end of line" (aka carriage return), PHP_EOL it is not considered as empty. Since end of lines are not always easy to spot this can be confusing.
Claudio Galdiolo 25-Mar-2017 12:20
Warning: an "empty" object is NOT considered to be empty
<?php
$var
= new stdClass(); // "empty" object
var_dump(empty($var)); // bool(false)
?>

I don't know if there is a standard way to test for "empty" objects, I personally use array casting:
<?php
$var
= new stdClass(); // "empty" object
$var = (array) $var; // cast to empty array
var_dump(empty($var)); // bool(true)
?>
mcfogw at gmail dot com 08-May-2016 02:40
I'm comparing behavior of `!` and `empty()`, find an undocumented behavior here.

just like cast-to-boolean, `empty()` cares about if SimpleXML object is made from emty tags.

`empty(simplexml_load_string('<root />'))` is TRUE

this behavior begins from php 5.1.0~7, in 5.0.x that's FALSE

proof here => https://3v4l.org/74Tc4
Javier Alfonso 11-Mar-2016 01:05
If you test an element of an array (like $_POST['key]), it test if the key doesn't exist or if it exist if its value is empty and never emit a warning.

For who don't want to test what happen if passed an array element here is my test and result.

<?php
$a
= array();
$b = array('key');
$c = array('key' => false);
$d = array('key' => 'La verdad nos hace libres');

echo (empty(
$a['key'])?'A empty':'A not empty'), ' - ', (empty($b['key'])?'B empty':'B not empty'), ' - ', (empty($c['key'])?'C empty':'C not empty'), ' - ', (empty($d['key'])?'D empty':'D not empty');
?>

And the result is:

    A empty - B empty - C empty - D not empty
your dot brother dot t at hotmail dot com 25-Dec-2014 09:38
(experienced in PHP 5.6.3) The `empty()` can't evaluate `__get()` results explicitly, so the `empty()` statement bellow always renders true
<?php
class Juice extends Liquid{
   protected
$apple;
   protected
$orange;
   public function
__get($name) {
      return
$this->$name;
   }
   public function
__construct($apple, $orange) {
     
$this->apple = $apple;
     
$this->orange = $orange;
   }
}

class
Glass {
   protected
$liquid;
   public function
__get($name) {
      return
$name == "liquid" ? $this->liquid : false;
   }
   public function
__construct() {
     
$this->juice = new Juice(3, 5);
   }
}

$glass = new Glass();
var_dump(empty($this->liquid->apple));

/**
 * The output is:
 * bool(true)
 */
?>

The correct way is to force the evaluation of `__get()` first, by using extra braces around implicit statements like this:
<?php
var_dump
(empty(($this->liquid->apple)));

/**
 * The output is:
 * bool(false)
 */
?>

So if you are using packages that utilize object oriented designs and magic methods like `__get()`, it's a good practice to always use double braces for `empty()` calls.
chrisdmiddleton at gmail dot com 09-Sep-2014 08:37
If you want to use empty() to evaluate an expression (not a variable), and you don't have PHP 5.5+, you can do it by wrapping the call to empty in a function, like so:
<?php
function is_empty($var) {

    return empty(
$var);

}
?>
Then you can do something like
<?php
if(is_empty(NULL)) {
 
/* ... */
}
?>
without issue, since the local variable $var is being tested rather than the expression in the function call itself.
turabgarip at gmail dot com 08-May-2014 04:16
Checking if a variable is empty or not when you have more than one will add so many similar lines to your code; and will require re-writing of course. Like for example;

<?php
if (!empty($a))
   
$myvar = $a;
elseif (!empty(
$b))
    
$myvar = $b;
//...
?>

If, for example $myvar should be pulled among 5 vars, you need to write it for 5 times. But in the below example, using $myvar = esor($var1, $var2, ...) will set it to first non-empty var.

<?php

function esor()
{
   
$arg_num = func_num_args();
   
// "No arguments" is empty string
   
if (!$arg_num) return '';
   
$args = func_get_args();
    for (
$i = 0; $i < $arg_num; $i++)
        if (!empty(
$args[$i]))
            return
$args[$i];
   
// Not found any filled var?
   
return ''; // Empty string is what you get
}

// For example;
mail(esor($settings['admin_mail'], $_ENV['SERVER_ADMIN']), 'Something went wrong', 'Error was foo');

?>

This will make it "one line code" no matter how many vars you have to check. Hope that helps.
Nanhe Kumar 31-Jan-2014 10:17
<?php
/**
* @author :  Nanhe Kumar <nanhe.kumar@gmail.com>
* List of all empty values
**/

$testCase = array(
   
1 => '',
   
2 => "",
   
3 => null,
   
4 => array(),
   
5 => FALSE,
   
6 => NULL,
   
7=>'0',
   
8=>0,
   
);

foreach (
$testCase as $k => $v) {
    if (empty(
$v)) {
        echo
"<br> $k=>$v is empty";
    }
}
/**
Output
1=> is empty
2=> is empty
3=> is empty
4=>Array is empty
5=> is empty
6=> is empty
7=>0 is empty
8=>0 is empty
**/
?>
bharris at nospam dot epic dot com 11-Nov-2013 08:59
XML::Unserializer produces unexpected results because empty($key) is true when $key = 0.

Example:

<?php
include("/usr/share/php/XML/Unserializer.php");
$xml= <<<EOD
<?xml version="1.0"?>
<groups _type="array">
    <XML_Serializer_Tag _originalKey="0" _type="array">
        <gid _type="integer">10</gid>
    </XML_Serializer_Tag>
    <XML_Serializer_Tag _originalKey="5" _type="array">
        <gid _type="integer">100</gid>
    </XML_Serializer_Tag>
</groups>
EOD;
$uns = new XML_Unserializer();
$res = $uns->unserialize($xml);
$recs = $uns->getUnserializedData();
print_r($recs);
?>

produces

Array
(
    [0] => Array
        (
            [gid] => 10
        )

    [5] => Array
        (
            [gid] => 100
        )
)

while

<?php
include("/usr/share/php/XML/Unserializer.php");
$xml= <<<EOD
<?xml version="1.0"?>
<groups _type="array">
    <XML_Serializer_Tag _originalKey="5" _type="array">
        <gid _type="integer">100</gid>
    </XML_Serializer_Tag>
    <XML_Serializer_Tag _originalKey="0" _type="array">
        <gid _type="integer">10</gid>
    </XML_Serializer_Tag>
</groups>
EOD;
$uns = new XML_Unserializer();
$res = $uns->unserialize($xml);
$recs = $uns->getUnserializedData();
print_r($recs);
?>

produces

Array
(
    [1] => Array
        (
            [gid] => 100
        )

    [6] => Array
        (
            [gid] => 10
        )
)

This is because the "empty" key value of 0 results in a push onto the end of the array, rather than an insertion at key position 0.
martin dot aarhof at gmail dot com 15-Mar-2012 08:38
<?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
?>
qeremy 07-Mar-2012 03:33
Simple solution for: "Fatal error: Can't use function return value in write context in ..."

<?php
function _empty($val) { return empty($val); }
?>
chris dot wisefool at gmail dot com 09-Sep-2011 12:44
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).
steven at nevvix dot com 02-May-2011 09:16
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.
phpsort 21-Jan-2011 11:13
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!
e dot klerks at i-bytes dot nl 08-Nov-2010 06:16
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.
rodolphe dot bodeau at free dot fr 25-Oct-2010 06:37
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
?>
ehsmeng 21-Sep-2010 05:25
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.
marko dot crni at gmail dot com 16-Sep-2010 11:06
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().
aidan1103 at yahoo dot com 26-Mar-2010 10:11
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.
Janci 24-Aug-2009 08:57
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.
denobasis-bozic et yahoo.com 18-Jul-2009 04:54
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=
mlibazisi mabandla 28-May-2009 02:47
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;
}
?>
emperoruk at dontspam dot hotmail dot com 08-May-2009 08:07
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
thomas at thomasnoest dot nl 28-Nov-2008 01:54
Note on the selfmade empty function below:

function_exists() returns false on language constructs and empty is a language construct.
Anonymous 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.
tom at tomwardrop dot com 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).
Greg Hartwig 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.
Andrea Giammarchi 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)''
Ed 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.
EllisGL 04-Oct-2007 02:48
Here's what I do for the zero issue issue:
if($val == '' && $val !== 0 && $val !== '0')
Antone Roundy 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.
rkulla2 at gmail dot com 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 =]
florian.sonner [at] t-online.de 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.
nobody at example dot com 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';
?>
nahpeps at gmx dot de 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
jmarbas at hotmail dot com 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);
?>
paul at worldwithoutwalls dot co dot uk 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
?>

CopyRight © 2008-2022 verySource.Com All Rights reserved. 京ICP备17048824号-1 京公网安备:11010502034788