如何使用PHP检查数组是否为空?

时间:2022-11-12 21:21:54

players will either be empty or a comma separated list (or a single value). What is the easiest way to check if it's empty? I'm assuming I can do so as soon as I fetch the $gameresult array into $gamerow? In this case it would probably be more efficient to skip exploding the $playerlist if it's empty, but for the sake of argument, how would I check if an array is empty as well?

玩家要么是空的,要么是逗号分隔的列表(或单个值)。检查它是否为空的最简单的方法是什么?我想只要我把$gameresult数组取到$gamerow中,我就可以这么做?在这种情况下,如果$playerlist是空的,那么跳过它可能会更有效,但是为了讨论,如何检查数组是否也是空的呢?

$gamerow = mysql_fetch_array($gameresult);
$playerlist = explode(",", $gamerow['players']);

17 个解决方案

#1


508  

If you just need to check if there are ANY elements in the array

如果只需要检查数组中是否有元素

if (empty($playerlist)) {
     // list is empty.
}

If you need to clean out empty values before checking (generally done to prevent explodeing weird strings):

如果您需要在检查前清除空值(通常是为了防止异常字符串爆炸):

foreach ($playerlist as $key => $value) {
    if (empty($value)) {
       unset($playerlist[$key]);
    }
}
if (empty($playerlist)) {
   //empty array
}

#2


113  

An empty array is falsey in PHP, so you don't even need to use empty() as others have suggested.

空数组是PHP中的falsey,因此您甚至不需要像其他人建议的那样使用empty()。

<?php
$playerList = array();
if (!$playerList) {
    echo "No players";
} else {
    echo "Explode stuff...";
}
// Output is: No players

PHP's empty() determines if a variable doesn't exist or has a falsey value (like array(), 0, null, false, etc).

PHP的empty()决定一个变量是否存在,或者有一个falsey值(如数组()、0、null、false等)。

In most cases you just want to check !$emptyVar. Use empty($emptyVar) if the variable might not have been set AND you don't wont to trigger an E_NOTICE; IMO this is generally a bad idea.

在大多数情况下,您只是想检查!$emptyVar。如果变量可能没有设置,并且您不会触发E_NOTICE,则使用empty($emptyVar);在我看来,这通常是个坏主意。

#3


62  

Some decent answers, but just thought I'd expand a bit to explain more clearly when PHP determines if an array is empty.

一些不错的答案,但我只是想扩展一下,以便更清楚地解释PHP何时确定数组为空。


Main Notes:

主要记录:

An array with a key (or keys) will be determined as NOT empty by PHP.

带有键(或键)的数组将由PHP确定为NOT empty。

As array values need keys to exist, having values or not in an array doesn't determine if it's empty, only if there are no keys (AND therefore no values).

由于数组值需要键存在,数组中是否有值并不决定它是否为空,只有在没有键(因此没有值)的情况下。

So checking an array with empty() doesn't simply tell you if you have values or not, it tells you if the array is empty, and keys are part of an array.

所以用empty()检查数组并不仅仅告诉你是否有值,它还告诉你数组是否为空,键是数组的一部分。


So consider how you are producing your array before deciding which checking method to use.
EG An array will have keys when a user submits your HTML form when each form field has an array name (ie name="array[]").
A non empty array will be produced for each field as there will be auto incremented key values for each form field's array.

因此,在决定使用哪种检查方法之前,请考虑如何生成数组。例如,当用户提交HTML表单时,当每个表单字段都有一个数组名(ie name="array[]")时,数组将具有键。将为每个字段生成一个非空数组,因为每个表单字段的数组将自动递增键值。

Take these arrays for example:

以这些数组为例:

/* Assigning some arrays */

// Array with user defined key and value
$ArrayOne = array("UserKeyA" => "UserValueA", "UserKeyB" => "UserValueB");

// Array with auto increment key and user defined value
// as a form field would return with user input
$ArrayTwo[] = "UserValue01";
$ArrayTwo[] = "UserValue02";

// Array with auto incremented key and no value
// as a form field would return without user input
$ArrayThree[] = '';
$ArrayThree[] = '';

If you echo out the array keys and values for the above arrays, you get the following:

如果您回显上述数组的数组键和值,则会得到以下结果:

ARRAY ONE:
[UserKeyA] => [UserValueA]
[UserKeyB] => [UserValueB]

数组1:[UserKeyA] => [UserValueA] [UserKeyB] => [UserValueB]

ARRAY TWO:
[0] => [UserValue01]
[1] => [UserValue02]

数组二:[0]=> [UserValue01] [1] => [UserValue02]

ARRAY THREE:
[0] => []
[1] => []

数组3:[0]=> [][1]=> []

And testing the above arrays with empty() returns the following results:

用empty()测试上述数组,得到如下结果:

ARRAY ONE:
$ArrayOne is not empty

数组1:$ArrayOne不是空的

ARRAY TWO:
$ArrayTwo is not empty

数组2:$ArrayTwo不是空的

ARRAY THREE:
$ArrayThree is not empty

数组3:$ArrayThree不是空的

An array will always be empty when you assign an array but don't use it thereafter, such as:

当你分配一个数组时,数组总是空的,但是以后不要使用它,例如:

$ArrayFour = array();

This will be empty, ie PHP will return TRUE when using if empty() on the above.

这将是空的,当在上面使用if empty()时,ie PHP将返回TRUE。

So if your array has keys - either by eg a form's input names or if you assign them manually (ie create an array with database column names as the keys but no values/data from the database), then the array will NOT be empty().

因此,如果数组中有键(例如表单的输入名),或者手动分配键(即创建一个以数据库列名为键的数组,但没有来自数据库的值/数据),那么数组就不是空的()。

In this case, you can loop the array in a foreach, testing if each key has a value. This is a good method if you need to run through the array anyway, perhaps checking the keys or sanitising data.

在这种情况下,可以在foreach中循环数组,测试每个键是否有值。如果您需要在数组中运行,这是一个很好的方法,可能是检查键或清除数据。

However it is not the best method if you simply need to know "if values exist" returns TRUE or FALSE. There are various methods to determine if an array has any values when it's know it will have keys. A function or class might be the best approach, but as always it depends on your environment and exact requirements, as well as other things such as what you currently do with the array (if anything).

但是,如果您只需要知道“如果存在值”返回TRUE或FALSE,那么这并不是最好的方法。有各种各样的方法来确定一个数组是否有任何值,当它知道它将有键时。函数或类可能是最好的方法,但是它始终取决于您的环境和确切的需求,以及其他事情,比如您当前对数组的处理(如果有的话)。


Here's an approach which uses very little code to check if an array has values:

这里有一种方法,使用很少的代码检查数组是否有值:

Using array_filter():
Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.

使用array_filter():迭代数组中的每个值,并将它们传递给回调函数。如果回调函数返回true,则返回数组的当前值到结果数组中。数组键保存。

$EmptyTestArray = array_filter($ArrayOne);

if (!empty($EmptyTestArray))
  {
    // do some tests on the values in $ArrayOne
  }
else
  {
    // Likely not to need an else, 
    // but could return message to user "you entered nothing" etc etc
  }

Running array_filter() on all three example arrays (created in the first code block in this answer) results in the following:

运行array_filter()在所有三个示例数组(在这个答案的第一个代码块中创建)的结果如下:

ARRAY ONE:
$arrayone is not empty

数组1:$arrayone不是空的

ARRAY TWO:
$arraytwo is not empty

数组2:$arraytwo不是空的

ARRAY THREE:
$arraythree is empty

数组3:$arraythree是空的

So when there are no values, whether there are keys or not, using array_filter() to create a new array and then check if the new array is empty shows if there were any values in the original array.
It is not ideal and a bit messy, but if you have a huge array and don't need to loop through it for any other reason, then this is the simplest in terms of code needed.

因此,当没有值时(无论是否有键),使用array_filter()创建一个新数组,然后检查新数组是否为空,显示原始数组中是否有值。它不是理想的,而且有点混乱,但是如果您有一个巨大的数组,并且不需要因为任何其他原因循环它,那么就所需的代码而言,这是最简单的。


I'm not experienced in checking overheads, but it would be good to know the differences between using array_filter() and foreach checking if a value is found.

我在检查开销方面没有经验,但是了解使用array_filter()和foreach检查是否有值是很好的。

Obviously benchmark would need to be on various parameters, on small and large arrays and when there are values and not etc.

显然,benchmark还需要在各种参数上,在小数组和大数组上,以及有值时,等等。

#4


14  

count($gamerow['players']) will be 0.

count($ gamerow['球员])将是0。

#5


7  

If you want to ascertain whether the variable you are testing is actually explicitly an empty array, you could use something like this:

如果您想要确定您正在测试的变量是否实际上是一个空数组,您可以使用以下方法:

if ($variableToTest === array()) {
    echo 'this is explicitly an empty array!';
}

#6


6  

is_array($detect) && empty($detect);

is_array

is_array

#7


3  

empty($gamerow['players'])

#8


3  

I use this code

我用这段代码

$variable = array();

if( count( $variable ) == 0 )
{
    echo "Array is Empty";
}
else
{
    echo "Array is not Empty";
}

But note that if the array has a large number of keys, this code will spend much time counting them, as compared to the other answers here.

但是请注意,如果数组有大量的键,与这里的其他答案相比,该代码将花费大量的时间来计算它们。

#9


3  

 $gamerow = mysql_fetch_array($gameresult);

if (!empty(($gamerow['players'])) {
   $playerlist = explode(",", $gamerow['players']);
}else{

  // do stuf if array is empty
}

#10


2  

if you are to check the array content you may use:

如果要检查数组内容,可以使用:

$arr = array();

if(!empty($arr)){
  echo "not empty";
}
else 
{
  echo "empty";
}

see here: http://codepad.org/EORE4k7v

在这里看到的:http://codepad.org/EORE4k7v

#11


2  

you can use array_filters which works great for all situations

您可以使用array_filter,它适用于所有情况

$ray_state = array_filter($myarray);

if (empty($ray_state)) {
 echo 'array is empty';
}else{
echo 'array is not empty';
}

#12


0  

Why has no one said this answer:

为什么没有人回答这个问题:

$array = [];

if($array == []) {
    // array is empty
}

#13


0  

I think the best way to determine if the array is empty or not is to use count() like so:

我认为确定数组是否为空的最好方法是像这样使用count():

if(count($array)) {
    return 'anything true goes here';
}else {
    return 'anything false'; 
}

#14


0  

I have solved this issue with following code.

我用下面的代码解决了这个问题。

$catArray=array();                          

$catIds=explode(',',$member['cat_id']);
if(!empty($catIds[0])){
foreach($catIds as $cat_id){
$catDetail=$this->Front_Category->get_category_detail($cat_id);
$catArray[]=$catDetail['allData']['cat_title'];
}
echo implode(',',$catArray);
}

#15


0  

This seems working for all cases

这似乎适用于所有情况

if(!empty(sizeof($array)))

#16


-1  

How about:

如何:

DepartmentPerSchool = array();
(empty(is_array($DepartmentPerSchool))) ? $DepartmentPerSchool //or echo is not empty : array('not set'=>'Not set. Contact Admin'); //or echo is empty

#17


-6  

The above solutions did not work for me. Rather I used more reliable way (it may have move overhead):

以上的解决方案对我不起作用。相反,我使用了更可靠的方式(它可能有移动开销):

$countarr = count($newArr); // Count the elements in an array.
$checkarr = "" ; //Initialize the value of variable to blank.
for($x=0;$x<$countarr;$x++)
{
  $checkarr = $newArr1[$x] ;
  if($checkarr != "" ) 
  {
       // do stuff if array is not empty.
  }
}

#1


508  

If you just need to check if there are ANY elements in the array

如果只需要检查数组中是否有元素

if (empty($playerlist)) {
     // list is empty.
}

If you need to clean out empty values before checking (generally done to prevent explodeing weird strings):

如果您需要在检查前清除空值(通常是为了防止异常字符串爆炸):

foreach ($playerlist as $key => $value) {
    if (empty($value)) {
       unset($playerlist[$key]);
    }
}
if (empty($playerlist)) {
   //empty array
}

#2


113  

An empty array is falsey in PHP, so you don't even need to use empty() as others have suggested.

空数组是PHP中的falsey,因此您甚至不需要像其他人建议的那样使用empty()。

<?php
$playerList = array();
if (!$playerList) {
    echo "No players";
} else {
    echo "Explode stuff...";
}
// Output is: No players

PHP's empty() determines if a variable doesn't exist or has a falsey value (like array(), 0, null, false, etc).

PHP的empty()决定一个变量是否存在,或者有一个falsey值(如数组()、0、null、false等)。

In most cases you just want to check !$emptyVar. Use empty($emptyVar) if the variable might not have been set AND you don't wont to trigger an E_NOTICE; IMO this is generally a bad idea.

在大多数情况下,您只是想检查!$emptyVar。如果变量可能没有设置,并且您不会触发E_NOTICE,则使用empty($emptyVar);在我看来,这通常是个坏主意。

#3


62  

Some decent answers, but just thought I'd expand a bit to explain more clearly when PHP determines if an array is empty.

一些不错的答案,但我只是想扩展一下,以便更清楚地解释PHP何时确定数组为空。


Main Notes:

主要记录:

An array with a key (or keys) will be determined as NOT empty by PHP.

带有键(或键)的数组将由PHP确定为NOT empty。

As array values need keys to exist, having values or not in an array doesn't determine if it's empty, only if there are no keys (AND therefore no values).

由于数组值需要键存在,数组中是否有值并不决定它是否为空,只有在没有键(因此没有值)的情况下。

So checking an array with empty() doesn't simply tell you if you have values or not, it tells you if the array is empty, and keys are part of an array.

所以用empty()检查数组并不仅仅告诉你是否有值,它还告诉你数组是否为空,键是数组的一部分。


So consider how you are producing your array before deciding which checking method to use.
EG An array will have keys when a user submits your HTML form when each form field has an array name (ie name="array[]").
A non empty array will be produced for each field as there will be auto incremented key values for each form field's array.

因此,在决定使用哪种检查方法之前,请考虑如何生成数组。例如,当用户提交HTML表单时,当每个表单字段都有一个数组名(ie name="array[]")时,数组将具有键。将为每个字段生成一个非空数组,因为每个表单字段的数组将自动递增键值。

Take these arrays for example:

以这些数组为例:

/* Assigning some arrays */

// Array with user defined key and value
$ArrayOne = array("UserKeyA" => "UserValueA", "UserKeyB" => "UserValueB");

// Array with auto increment key and user defined value
// as a form field would return with user input
$ArrayTwo[] = "UserValue01";
$ArrayTwo[] = "UserValue02";

// Array with auto incremented key and no value
// as a form field would return without user input
$ArrayThree[] = '';
$ArrayThree[] = '';

If you echo out the array keys and values for the above arrays, you get the following:

如果您回显上述数组的数组键和值,则会得到以下结果:

ARRAY ONE:
[UserKeyA] => [UserValueA]
[UserKeyB] => [UserValueB]

数组1:[UserKeyA] => [UserValueA] [UserKeyB] => [UserValueB]

ARRAY TWO:
[0] => [UserValue01]
[1] => [UserValue02]

数组二:[0]=> [UserValue01] [1] => [UserValue02]

ARRAY THREE:
[0] => []
[1] => []

数组3:[0]=> [][1]=> []

And testing the above arrays with empty() returns the following results:

用empty()测试上述数组,得到如下结果:

ARRAY ONE:
$ArrayOne is not empty

数组1:$ArrayOne不是空的

ARRAY TWO:
$ArrayTwo is not empty

数组2:$ArrayTwo不是空的

ARRAY THREE:
$ArrayThree is not empty

数组3:$ArrayThree不是空的

An array will always be empty when you assign an array but don't use it thereafter, such as:

当你分配一个数组时,数组总是空的,但是以后不要使用它,例如:

$ArrayFour = array();

This will be empty, ie PHP will return TRUE when using if empty() on the above.

这将是空的,当在上面使用if empty()时,ie PHP将返回TRUE。

So if your array has keys - either by eg a form's input names or if you assign them manually (ie create an array with database column names as the keys but no values/data from the database), then the array will NOT be empty().

因此,如果数组中有键(例如表单的输入名),或者手动分配键(即创建一个以数据库列名为键的数组,但没有来自数据库的值/数据),那么数组就不是空的()。

In this case, you can loop the array in a foreach, testing if each key has a value. This is a good method if you need to run through the array anyway, perhaps checking the keys or sanitising data.

在这种情况下,可以在foreach中循环数组,测试每个键是否有值。如果您需要在数组中运行,这是一个很好的方法,可能是检查键或清除数据。

However it is not the best method if you simply need to know "if values exist" returns TRUE or FALSE. There are various methods to determine if an array has any values when it's know it will have keys. A function or class might be the best approach, but as always it depends on your environment and exact requirements, as well as other things such as what you currently do with the array (if anything).

但是,如果您只需要知道“如果存在值”返回TRUE或FALSE,那么这并不是最好的方法。有各种各样的方法来确定一个数组是否有任何值,当它知道它将有键时。函数或类可能是最好的方法,但是它始终取决于您的环境和确切的需求,以及其他事情,比如您当前对数组的处理(如果有的话)。


Here's an approach which uses very little code to check if an array has values:

这里有一种方法,使用很少的代码检查数组是否有值:

Using array_filter():
Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.

使用array_filter():迭代数组中的每个值,并将它们传递给回调函数。如果回调函数返回true,则返回数组的当前值到结果数组中。数组键保存。

$EmptyTestArray = array_filter($ArrayOne);

if (!empty($EmptyTestArray))
  {
    // do some tests on the values in $ArrayOne
  }
else
  {
    // Likely not to need an else, 
    // but could return message to user "you entered nothing" etc etc
  }

Running array_filter() on all three example arrays (created in the first code block in this answer) results in the following:

运行array_filter()在所有三个示例数组(在这个答案的第一个代码块中创建)的结果如下:

ARRAY ONE:
$arrayone is not empty

数组1:$arrayone不是空的

ARRAY TWO:
$arraytwo is not empty

数组2:$arraytwo不是空的

ARRAY THREE:
$arraythree is empty

数组3:$arraythree是空的

So when there are no values, whether there are keys or not, using array_filter() to create a new array and then check if the new array is empty shows if there were any values in the original array.
It is not ideal and a bit messy, but if you have a huge array and don't need to loop through it for any other reason, then this is the simplest in terms of code needed.

因此,当没有值时(无论是否有键),使用array_filter()创建一个新数组,然后检查新数组是否为空,显示原始数组中是否有值。它不是理想的,而且有点混乱,但是如果您有一个巨大的数组,并且不需要因为任何其他原因循环它,那么就所需的代码而言,这是最简单的。


I'm not experienced in checking overheads, but it would be good to know the differences between using array_filter() and foreach checking if a value is found.

我在检查开销方面没有经验,但是了解使用array_filter()和foreach检查是否有值是很好的。

Obviously benchmark would need to be on various parameters, on small and large arrays and when there are values and not etc.

显然,benchmark还需要在各种参数上,在小数组和大数组上,以及有值时,等等。

#4


14  

count($gamerow['players']) will be 0.

count($ gamerow['球员])将是0。

#5


7  

If you want to ascertain whether the variable you are testing is actually explicitly an empty array, you could use something like this:

如果您想要确定您正在测试的变量是否实际上是一个空数组,您可以使用以下方法:

if ($variableToTest === array()) {
    echo 'this is explicitly an empty array!';
}

#6


6  

is_array($detect) && empty($detect);

is_array

is_array

#7


3  

empty($gamerow['players'])

#8


3  

I use this code

我用这段代码

$variable = array();

if( count( $variable ) == 0 )
{
    echo "Array is Empty";
}
else
{
    echo "Array is not Empty";
}

But note that if the array has a large number of keys, this code will spend much time counting them, as compared to the other answers here.

但是请注意,如果数组有大量的键,与这里的其他答案相比,该代码将花费大量的时间来计算它们。

#9


3  

 $gamerow = mysql_fetch_array($gameresult);

if (!empty(($gamerow['players'])) {
   $playerlist = explode(",", $gamerow['players']);
}else{

  // do stuf if array is empty
}

#10


2  

if you are to check the array content you may use:

如果要检查数组内容,可以使用:

$arr = array();

if(!empty($arr)){
  echo "not empty";
}
else 
{
  echo "empty";
}

see here: http://codepad.org/EORE4k7v

在这里看到的:http://codepad.org/EORE4k7v

#11


2  

you can use array_filters which works great for all situations

您可以使用array_filter,它适用于所有情况

$ray_state = array_filter($myarray);

if (empty($ray_state)) {
 echo 'array is empty';
}else{
echo 'array is not empty';
}

#12


0  

Why has no one said this answer:

为什么没有人回答这个问题:

$array = [];

if($array == []) {
    // array is empty
}

#13


0  

I think the best way to determine if the array is empty or not is to use count() like so:

我认为确定数组是否为空的最好方法是像这样使用count():

if(count($array)) {
    return 'anything true goes here';
}else {
    return 'anything false'; 
}

#14


0  

I have solved this issue with following code.

我用下面的代码解决了这个问题。

$catArray=array();                          

$catIds=explode(',',$member['cat_id']);
if(!empty($catIds[0])){
foreach($catIds as $cat_id){
$catDetail=$this->Front_Category->get_category_detail($cat_id);
$catArray[]=$catDetail['allData']['cat_title'];
}
echo implode(',',$catArray);
}

#15


0  

This seems working for all cases

这似乎适用于所有情况

if(!empty(sizeof($array)))

#16


-1  

How about:

如何:

DepartmentPerSchool = array();
(empty(is_array($DepartmentPerSchool))) ? $DepartmentPerSchool //or echo is not empty : array('not set'=>'Not set. Contact Admin'); //or echo is empty

#17


-6  

The above solutions did not work for me. Rather I used more reliable way (it may have move overhead):

以上的解决方案对我不起作用。相反,我使用了更可靠的方式(它可能有移动开销):

$countarr = count($newArr); // Count the elements in an array.
$checkarr = "" ; //Initialize the value of variable to blank.
for($x=0;$x<$countarr;$x++)
{
  $checkarr = $newArr1[$x] ;
  if($checkarr != "" ) 
  {
       // do stuff if array is not empty.
  }
}