php 如何使用PHP检查数组是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2216052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check whether an array is empty using PHP?
提问by aslum
playerswill 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 $gameresultarray into $gamerow? In this case it would probably be more efficient to skip exploding the $playerlistif it's empty, but for the sake of argument, how would I check if an array is empty as well?
players将为空或逗号分隔的列表(或单个值)。检查它是否为空的最简单方法是什么?我假设我可以在将$gameresult数组提取到$gamerow? 在这种情况下,$playerlist如果它是空的,跳过爆炸可能会更有效,但为了论证,我将如何检查数组是否也为空?
$gamerow = mysql_fetch_array($gameresult);
$playerlist = explode(",", $gamerow['players']);
回答by Tyler Carter
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):
如果您需要在检查之前清除空值(通常这样做是为了防止出现explode奇怪的字符串):
foreach ($playerlist as $key => $value) {
if (empty($value)) {
unset($playerlist[$key]);
}
}
if (empty($playerlist)) {
//empty array
}
回答by Cobby
An empty array is falsey in PHP, so you don't even need to use empty()as others have suggested.
PHP 中的空数组是错误的,因此您甚至不需要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的值(如array(),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. 使用empty($emptyVar)如果变量可能没有已定,你不这样做不会触发E_NOTICE; IMO 这通常是一个坏主意。
回答by James
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 emptyby PHP.
带有键(或键)的数组将被PHP确定为非空。
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 willhave keys when a user submits your HTML form when each form field has an array name (ie name="array[]").
A non emptyarray will be produced for each field as there will be auto incremented key values for each form field's array.
因此,在决定使用哪种检查方法之前,请考虑如何生成数组。
EG当用户提交您的 HTML 表单时,当每个表单字段都有一个数组名称(即)时,数组将包含键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]ARRAY TWO:
[0] => [UserValue01]
[1] => [UserValue02]ARRAY THREE:
[0] => []
[1] => []
数组一:
[UserKeyA] => [UserValueA]
[UserKeyB] => [UserValueB]数组二:
[0] => [UserValue01]
[1] => [UserValue02]数组三:
[0] => []
[1] => []
And testing the above arrays with empty()returns the following results:
并测试上述数组empty()返回以下结果:
ARRAY ONE:
$ArrayOne is not emptyARRAY TWO:
$ArrayTwo is not emptyARRAY THREE:
$ArrayThree is not empty
数组一:
$ArrayOne 不为空数组二:
$ArrayTwo 不为空数组三:
$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.
这将是空的,即 PHP 在使用empty()上面的if 时将返回 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().
因此,如果您的数组具有键 - 例如通过表单的输入名称或如果您手动分配它们(即创建一个以数据库列名作为键但没有来自数据库的值/数据的数组),那么该数组将不会是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 TRUEor 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 emptyARRAY TWO:
$arraytwo is not emptyARRAY THREE:
$arraythree is empty
数组一:
$arrayone 不为空数组二:
$arraytwo 不为空数组三:
$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 foreachchecking 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.
显然,基准测试需要针对各种参数、小型和大型数组以及何时有值而不是等。
回答by Ignacio Vazquez-Abrams
count($gamerow['players'])will be 0.
回答by Tim Ogilvy
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!';
}
回答by kenorb
If you'd like to exclude the false or empty rows (such as 0 => ''), where using empty()will fail, you can try:
如果您想排除 false 或空行(例如0 => ''),使用empty()会失败,您可以尝试:
if (array_filter($playerlist) == []) {
// Array is empty!
}
array_filter(): If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.
array_filter(): 如果未提供回调,则数组中所有等于 FALSE 的条目(请参阅转换为布尔值)将被删除。
If you'd like to remove all NULL, FALSE and empty strings (''), but leave zero values (0), you can use strlenas a callback, e.g.:
如果您想删除所有 NULL、FALSE 和空字符串 ( ''),但保留零值 ( 0),您可以将其strlen用作回调,例如:
$is_empty = array_filter($playerlist, 'strlen') == [];
回答by Rob
Why has no one said this answer:
为什么没人说这个答案:
$array = [];
if($array == []) {
// array is empty
}
回答by Kaan
I ran the benchmark included at the end of the post. To compare the methods:
我运行了帖子末尾的基准测试。要比较这些方法:
count($arr) == 0: countempty($arr): empty$arr == []: comp(bool) $arr: cast
count($arr) == 0: 数数empty($arr): 空的$arr == []:补偿(bool) $arr: 投掷
and got the following results
并得到以下结果
Contents \method | count | empty | comp | cast |
------------------|--------------|--------------|--------------|--------------|
Empty |/* 1.213138 */|/* 1.070011 */|/* 1.628529 */| 1.051795 |
Uniform |/* 1.206680 */| 1.047339 |/* 1.498836 */|/* 1.052737 */|
Integer |/* 1.209668 */|/* 1.079858 */|/* 1.486134 */| 1.051138 |
String |/* 1.242137 */| 1.049148 |/* 1.630259 */|/* 1.056610 */|
Mixed |/* 1.229072 */|/* 1.068569 */|/* 1.473339 */| 1.064111 |
Associative |/* 1.206311 */| 1.053642 |/* 1.480637 */|/* 1.137740 */|
------------------|--------------|--------------|--------------|--------------|
Total |/* 7.307005 */| 6.368568 |/* 9.197733 */|/* 6.414131 */|
The difference between empty and casting to a boolean are insignificant. I've run this test multiple times and they appear to be essentially equivalent. The contents of the arrays do not seem to play a significant role. The two produce the opposite results but the logical negation is barely enough to push casting to winning most of the time so I personally prefer empty for the sake of legibility in either case.
空和转换为布尔值之间的区别是微不足道的。我已经多次运行此测试,它们似乎基本相同。数组的内容似乎并不重要。两者产生相反的结果,但逻辑否定几乎不足以在大多数情况下推动铸造获胜,所以我个人更喜欢空的,为了在任何一种情况下的易读性。
#!/usr/bin/php
<?php
// 012345678
$nt = 90000000;
$arr0 = [];
$arr1 = [];
$arr2 = [];
$arr3 = [];
$arr4 = [];
$arr5 = [];
for ($i = 0; $i < 500000; $i++) {
$arr1[] = 0;
$arr2[] = $i;
$arr3[] = md5($i);
$arr4[] = $i % 2 ? $i : md5($i);
$arr5[md5($i)] = $i;
}
$t00 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
count($arr0) == 0;
}
$t01 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
empty($arr0);
}
$t02 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
$arr0 == [];
}
$t03 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
(bool) $arr0;
}
$t04 = microtime(true);
$t10 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
count($arr1) == 0;
}
$t11 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
empty($arr1);
}
$t12 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
$arr1 == [];
}
$t13 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
(bool) $arr1;
}
$t14 = microtime(true);
/* ------------------------------ */
$t20 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
count($arr2) == 0;
}
$t21 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
empty($arr2);
}
$t22 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
$arr2 == [];
}
$t23 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
(bool) $arr2;
}
$t24 = microtime(true);
/* ------------------------------ */
$t30 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
count($arr3) == 0;
}
$t31 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
empty($arr3);
}
$t32 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
$arr3 == [];
}
$t33 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
(bool) $arr3;
}
$t34 = microtime(true);
/* ------------------------------ */
$t40 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
count($arr4) == 0;
}
$t41 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
empty($arr4);
}
$t42 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
$arr4 == [];
}
$t43 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
(bool) $arr4;
}
$t44 = microtime(true);
/* ----------------------------------- */
$t50 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
count($arr5) == 0;
}
$t51 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
empty($arr5);
}
$t52 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
$arr5 == [];
}
$t53 = microtime(true);
for ($i = 0; $i < $nt; $i++) {
(bool) $arr5;
}
$t54 = microtime(true);
/* ----------------------------------- */
$t60 = $t00 + $t10 + $t20 + $t30 + $t40 + $t50;
$t61 = $t01 + $t11 + $t21 + $t31 + $t41 + $t51;
$t62 = $t02 + $t12 + $t22 + $t32 + $t42 + $t52;
$t63 = $t03 + $t13 + $t23 + $t33 + $t43 + $t53;
$t64 = $t04 + $t14 + $t24 + $t34 + $t44 + $t54;
/* ----------------------------------- */
$ts0[1] = number_format(round($t01 - $t00, 6), 6);
$ts0[2] = number_format(round($t02 - $t01, 6), 6);
$ts0[3] = number_format(round($t03 - $t02, 6), 6);
$ts0[4] = number_format(round($t04 - $t03, 6), 6);
$min_idx = array_keys($ts0, min($ts0))[0];
foreach ($ts0 as $idx => $val) {
if ($idx == $min_idx) {
$ts0[$idx] = " $val ";
} else {
$ts0[$idx] = "/* $val */";
}
}
$ts1[1] = number_format(round($t11 - $t10, 6), 6);
$ts1[2] = number_format(round($t12 - $t11, 6), 6);
$ts1[3] = number_format(round($t13 - $t12, 6), 6);
$ts1[4] = number_format(round($t14 - $t13, 6), 6);
$min_idx = array_keys($ts1, min($ts1))[0];
foreach ($ts1 as $idx => $val) {
if ($idx == $min_idx) {
$ts1[$idx] = " $val ";
} else {
$ts1[$idx] = "/* $val */";
}
}
$ts2[1] = number_format(round($t21 - $t20, 6), 6);
$ts2[2] = number_format(round($t22 - $t21, 6), 6);
$ts2[3] = number_format(round($t23 - $t22, 6), 6);
$ts2[4] = number_format(round($t24 - $t23, 6), 6);
$min_idx = array_keys($ts2, min($ts2))[0];
foreach ($ts2 as $idx => $val) {
if ($idx == $min_idx) {
$ts2[$idx] = " $val ";
} else {
$ts2[$idx] = "/* $val */";
}
}
$ts3[1] = number_format(round($t31 - $t30, 6), 6);
$ts3[2] = number_format(round($t32 - $t31, 6), 6);
$ts3[3] = number_format(round($t33 - $t32, 6), 6);
$ts3[4] = number_format(round($t34 - $t33, 6), 6);
$min_idx = array_keys($ts3, min($ts3))[0];
foreach ($ts3 as $idx => $val) {
if ($idx == $min_idx) {
$ts3[$idx] = " $val ";
} else {
$ts3[$idx] = "/* $val */";
}
}
$ts4[1] = number_format(round($t41 - $t40, 6), 6);
$ts4[2] = number_format(round($t42 - $t41, 6), 6);
$ts4[3] = number_format(round($t43 - $t42, 6), 6);
$ts4[4] = number_format(round($t44 - $t43, 6), 6);
$min_idx = array_keys($ts4, min($ts4))[0];
foreach ($ts4 as $idx => $val) {
if ($idx == $min_idx) {
$ts4[$idx] = " $val ";
} else {
$ts4[$idx] = "/* $val */";
}
}
$ts5[1] = number_format(round($t51 - $t50, 6), 6);
$ts5[2] = number_format(round($t52 - $t51, 6), 6);
$ts5[3] = number_format(round($t53 - $t52, 6), 6);
$ts5[4] = number_format(round($t54 - $t53, 6), 6);
$min_idx = array_keys($ts5, min($ts5))[0];
foreach ($ts5 as $idx => $val) {
if ($idx == $min_idx) {
$ts5[$idx] = " $val ";
} else {
$ts5[$idx] = "/* $val */";
}
}
$ts6[1] = number_format(round($t61 - $t60, 6), 6);
$ts6[2] = number_format(round($t62 - $t61, 6), 6);
$ts6[3] = number_format(round($t63 - $t62, 6), 6);
$ts6[4] = number_format(round($t64 - $t63, 6), 6);
$min_idx = array_keys($ts6, min($ts6))[0];
foreach ($ts6 as $idx => $val) {
if ($idx == $min_idx) {
$ts6[$idx] = " $val ";
} else {
$ts6[$idx] = "/* $val */";
}
}
echo " | count | empty | comp | cast |\n";
echo "-------------|--------------|--------------|--------------|--------------|\n";
echo " Empty |";
echo $ts0[1] . '|';
echo $ts0[2] . '|';
echo $ts0[3] . '|';
echo $ts0[4] . "|\n";
echo " Uniform |";
echo $ts1[1] . '|';
echo $ts1[2] . '|';
echo $ts1[3] . '|';
echo $ts1[4] . "|\n";
echo " Integer |";
echo $ts2[1] . '|';
echo $ts2[2] . '|';
echo $ts2[3] . '|';
echo $ts2[4] . "|\n";
echo " String |";
echo $ts3[1] . '|';
echo $ts3[2] . '|';
echo $ts3[3] . '|';
echo $ts3[4] . "|\n";
echo " Mixed |";
echo $ts4[1] . '|';
echo $ts4[2] . '|';
echo $ts4[3] . '|';
echo $ts4[4] . "|\n";
echo " Associative |";
echo $ts5[1] . '|';
echo $ts5[2] . '|';
echo $ts5[3] . '|';
echo $ts5[4] . "|\n";
echo "-------------|--------------|--------------|--------------|--------------|\n";
echo " Total |";
echo $ts6[1] . '|';
echo $ts6[2] . '|';
echo $ts6[3] . '|';
echo $ts6[4] . "|\n";
回答by PJately
In my opinion the simplest way for an indexed array would be simply:
在我看来,索引数组最简单的方法就是:
if ($array) {
//Array is not empty...
}
An 'if' condition on the array would evaluate to true if the array is not emptyand false if the array is empty. This is notapplicable to associative arrays.
如果数组不为空,则数组上的“if”条件将评估为true ,如果数组为空则为 false。这是不是适用于关联数组。

