php 检查空数组:计数与空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2216110/
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
Checking for empty arrays: count vs empty
提问by Dan McGrath
This question on 'How to tell if a PHP array is empty' had me thinking of this question
这个关于“如何判断 PHP 数组是否为空”的问题让我想到了这个问题
Is there a reason that countshould be used instead of emptywhen determining if an array is empty or not?
是否有理由在确定数组是否为空时count使用而不是使用empty?
My personal thought would be if the 2 are equivalent for the case of empty arrays you should use emptybecause it gives a boolean answer to a boolean question. From the question linked above, it seems that count($var) == 0is the popular method. To me, while technically correct, makes no sense. E.g. Q: $var, are you empty? A: 7. Hmmm...
我个人的想法是如果 2 等价于您应该使用的空数组的情况,empty因为它为布尔问题提供了布尔答案。从上面链接的问题来看,这似乎count($var) == 0是流行的方法。对我来说,虽然技术上是正确的,但毫无意义。例如问:$var,你是空的吗?答:7。嗯...
Is there a reason I should use count == 0instead or just a matter of personal taste?
是否有理由我应该使用它count == 0或只是个人品味的问题?
As pointed out by others in comments for a now deleted answer, countwill have performance impacts for large arrays because it will have to count all elements, whereas emptycan stop as soon as it knows it isn't empty. So, if they give the same results in this case, but countis potentially inefficient, why would we ever use count($var) == 0?
正如其他人在对现已删除的答案的评论中指出的那样,count将对大型数组的性能产生影响,因为它必须计算所有元素,而empty一旦知道它不为空就可以停止。所以,如果他们在这种情况下给出相同的结果,但count可能效率低下,我们为什么要使用count($var) == 0?
回答by prodigitalson
I generally use empty. Im not sure why people would use count really - If the array is large then count takes longer/has more overhead. If you simply need to know whether or not the array is empty then use empty.
我一般用empty. 我不知道为什么人们真的会使用 count - 如果数组很大,那么 count 需要更长的时间/有更多的开销。如果您只需要知道数组是否为空,则使用空。
回答by Satake
I was curious to see which one was actually faster so I made a simple script to benchmark those functions.
我很想知道哪个实际上更快,所以我制作了一个简单的脚本来对这些函数进行基准测试。
<?php
function benchmark($name, $iterations, $action){
$time=microtime(true);
for($i=0;$i<=$iterations;++$i){
$action();
}
echo $name . ' ' . round(microtime(true)-$time, 6) . "\n";
}
$iterations = 1000000;
$x = array();
$y = range(0, 10000000);
$actions = array(
"Empty empty()" => function() use($x){
empty($x);
},
"Empty count()" => function() use($x){
count($x);
},
"Full empty()" => function() use($y){
empty($y);
},
"Full count()" => function() use($y){
count($y);
},
############
"IF empty empty()" => function() use($x){
if(empty($x)){ $t=1; }
},
"IF empty count()" => function() use($x){
if(count($x)){ $t=1; }
},
"IF full empty()" => function() use($y){
if(empty($y)){ $t=1; }
},
"IF full count()" => function() use($y){
if(count($y)){ $t=1; }
},
############
"OR empty empty()" => function() use($x){
empty($x) OR $t=1;
},
"OR empty count()" => function() use($x){
count($x) OR $t=1;
},
"OR full empty()" => function() use($y){
empty($y) OR $t=1;
},
"OR full count()" => function() use($y){
count($y) OR $t=1;
},
############
"IF/ELSE empty empty()" => function() use($x){
if(empty($x)){ $t=1; } else { $t=2; }
},
"IF/ELSE empty count()" => function() use($x){
if(count($x)){ $t=1; } else { $t=2; }
},
"IF/ELSE full empty()" => function() use($y){
if(empty($y)){ $t=1; } else { $t=2; }
},
"IF/ELSE full count()" => function() use($y){
if(count($y)){ $t=1; } else { $t=2; }
},
############
"( ? : ) empty empty()" => function() use($x){
$t = (empty($x) ? 1 : 2);
},
"( ? : ) empty count()" => function() use($x){
$t = (count($x) ? 1 : 2);
},
"( ? : ) full empty()" => function() use($y){
$t = (empty($y) ? 1 : 2);
},
"( ? : ) full count()" => function() use($y){
$t = (count($y) ? 1 : 2);
}
);
foreach($actions as $name => $action){
benchmark($name, $iterations, $action);
}
//END
Since I was doing it I also tried to check the performance doing operations that would normally be associated with count()/empty()
由于我正在这样做,我还尝试检查执行通常与 count()/empty() 相关联的操作的性能
Using PHP 5.4.39:
使用 PHP 5.4.39:
Empty empty() 0.118691
Empty count() 0.218974
Full empty() 0.133747
Full count() 0.216424
IF empty empty() 0.166474
IF empty count() 0.235922
IF full empty() 0.120642
IF full count() 0.248273
OR empty empty() 0.123875
OR empty count() 0.258665
OR full empty() 0.157839
OR full count() 0.224869
IF/ELSE empty empty() 0.167004
IF/ELSE empty count() 0.263351
IF/ELSE full empty() 0.145794
IF/ELSE full count() 0.248425
( ? : ) empty empty() 0.169487
( ? : ) empty count() 0.265701
( ? : ) full empty() 0.149847
( ? : ) full count() 0.252891
Using HipHop VM 3.6.1 (dbg)
使用 HipHop VM 3.6.1 (dbg)
Empty empty() 0.210652
Empty count() 0.212123
Full empty() 0.206016
Full count() 0.204722
IF empty empty() 0.227852
IF empty count() 0.219821
IF full empty() 0.220823
IF full count() 0.221397
OR empty empty() 0.218813
OR empty count() 0.220105
OR full empty() 0.229118
OR full count() 0.221787
IF/ELSE empty empty() 0.221499
IF/ELSE empty count() 0.221274
IF/ELSE full empty() 0.221879
IF/ELSE full count() 0.228737
( ? : ) empty empty() 0.224143
( ? : ) empty count() 0.222459
( ? : ) full empty() 0.221606
( ? : ) full count() 0.231288
Conclusions if you're using PHP:
如果您使用的是 PHP 的结论:
empty() is much much faster than count() in both scenarios, with an empty and populated array
count() performs the same with a full or empty array.
Doing a simple IF or just a Boolean operation is the same.
IF/ELSE is very slightly more efficient than ( ? : ). Unless you're doing billions of iterations with expressions in the middle it is completely insignificant.
empty() 在这两种情况下都比 count() 快得多,数组是空的和填充的
count() 对完整或空数组执行相同的操作。
做一个简单的 IF 或只是一个布尔运算是一样的。
IF/ELSE 比 ( ? : ) 稍微高效一点。除非您在中间使用表达式进行数十亿次迭代,否则它完全无关紧要。
Conclusions if you're using HHVM:
如果您使用 HHVM 的结论:
empty() is a teeny-weeny bit faster than count() but insignificantly so.
[ The rest is the same as in PHP ]
empty() 比 count() 快一点,但微不足道。
[其余与PHP相同]
In conclusion of the conclusion, if you just need to know if the array is empty always use empty();
总结一下,如果您只需要知道数组是否为空,请始终使用 empty();
This was just a curious test simply done without taking many things into account. It is just a proof of concept and might not reflect operations in production.
这只是一个奇怪的测试,只是在没有考虑很多事情的情况下完成的。它只是概念证明,可能不反映生产中的操作。
回答by Laurent le Beau-Martin
I think it's only personal preference. Some people might say emptyis faster (e.g. http://jamessocol.com/projects/count_vs_empty.php) while others might say countis better since it was originally made for arrays. emptyis more general and can be applied to other types.
我认为这只是个人喜好。有些人可能会说empty更快(例如http://jamessocol.com/projects/count_vs_empty.php),而其他人可能会说count更好,因为它最初是为数组制作的。empty更通用,可以应用于其他类型。
php.net gives the following warning for countthough :
php.net 给出了以下警告count:
count() may return 0 for a variable that isn't set, but it may also return 0 for a variable that has been initialized with an empty array. Use isset() to test if a variable is set.
count() 可能会为未设置的变量返回 0,但对于已使用空数组初始化的变量,它也可能会返回 0。使用 isset() 测试是否设置了变量。
In other words, if the variable is not set, you will get a notice from PHP saying it's undefined. Therefore, before using count, it would be preferable to check the variable with isset. This is not necessary with empty.
换句话说,如果变量未设置,您将收到来自 PHP 的通知,说它未定义。因此,在使用之前count,最好使用 来检查变量isset。这对于empty.
回答by dev-null-dweller
Is there a reason that count should be used instead of empty when determining if an array is empty or not?
在确定数组是否为空时,是否有理由使用计数而不是空?
There is, when you need to do something on non-empty array knowing it's size:
有,当你需要在知道它的大小的非空数组上做一些事情时:
if( 0 < ( $cnt = count($array) ) )
{
echo "Your array size is: $cnt";
}
else
echo "Too bad, your array is empty :(";
But I wouldn't recommend using count, unless you are 100% sure, that what you are counting is an array. Lately I have been debugging code, where on error function was returning FALSEinstead of empty array, and what I discovered was:
但我不建议使用计数,除非您 100% 确定您正在计数的是一个数组。最近我一直在调试代码,错误函数返回FALSE而不是空数组,我发现的是:
var_dump(count(FALSE));
output:
输出:
int 1
So since then I am using emptyor if(array() === $array)to be sure that I have arraythat is empty.
所以从那以后我使用empty或if(array() === $array)确保我有空的数组。
回答by Ryan
count()seems to work better with array-like interfaces that implement ArrayAccess/Countable. empty()returns true for these kinds of objects even if they have no elements. Typically these classes will implement the Countableinterface, so if the question is "Does this collection contain elements?" without making an assumption about the implementation, then count()is a better option.
count()似乎与实现ArrayAccess/Countable. empty()对于这些类型的对象,即使它们没有元素也返回 true。通常这些类将实现Countable接口,所以如果问题是“这个集合是否包含元素?” 如果不对实现做出假设,那么count()是更好的选择。
回答by Ryan
Alternatively, you can cast the variable as a boolean (implicitly or explicitly):
或者,您可以将变量转换为布尔值(隐式或显式):
if( $value )
{
// array is not empty
}
if( (bool) $value )
{
// array is still not empty
}
This method does generate an E_NOTICEif the variable is not defined, similarly to count().
E_NOTICE如果未定义变量,则此方法确实会生成,类似于count()。
For more information, see the PHP Manual page on type comparisons.
有关更多信息,请参阅有关类型比较的 PHP 手册页。
回答by simonhamp
My personal preference is more for coding elegance (in relation to my specific use-case). I agree with Dan McG inasmuch that count() isn't responding with the correct datatype (in this case boolean) for the test in question forcing the developer to write more code to fill an 'if' statement.
我个人更喜欢编码优雅(与我的特定用例有关)。我同意 Dan McG 的观点,因为 count() 没有以正确的数据类型(在本例中为布尔值)响应所讨论的测试,迫使开发人员编写更多代码来填充“if”语句。
Whether this has any significant impact on performance is only debatable for extremely large arrays (which you probably won't have enough memory allocation for anyway in most setups).
这是否对性能有任何显着影响仅对于超大阵列(在大多数设置中您可能没有足够的内存分配)存在争议。
Particularly when it comes to PHP's $_POST array, it seems much more "logical" in my opinion to write/see:
特别是当涉及到 PHP 的 $_POST 数组时,在我看来写/看似乎更“合乎逻辑”:
if ( !empty ( $_POST ) ) {
// deal with postdata
}
回答by xchiltonx
Hope this might help someone even though it has already been answered (and debated some what). In my own scenario, I know all my arrays all have 7 elements (checks were made earlier in my code) and I am performing an array_diffwhich of course returns an array of zero when equal.
希望这可能对某人有所帮助,即使它已经得到了回答(并讨论了一些什么)。在我自己的场景中,我知道我所有的数组都有 7 个元素(在我的代码中早些时候进行了检查)并且我正在执行一个array_diff当然在相等时返回零数组。
I had 34 sec for countand 17 sec for empty. Both give me the same calculations so my code is still fine.
我有 34 秒count和 17 秒empty。两者都给我相同的计算,所以我的代码仍然很好。
However you can also try the ==or ===as in PHP - Check if two arrays are equal. The best I would say is try countvs emptyvs == empty array, then see which gives your own best perfs. In my case countwas the slowest so I am using emptynow... will be checking serializenext
然而,你也可以尝试==或===为PHP -检查两个数组是相等的。我想说的最好的是 try countvs emptyvs == empty array,然后看看哪个给出了你自己最好的性能。在我的情况count是最慢的所以我使用的empty,现在...将检查serialize下一个
回答by Sdlion
Since a variable parsed as negative would return int(1)with count()
由于变量解析为负将返回int(1)与count()
I prefer ($array === [] || !$array)to test for an empty array.
我更喜欢($array === [] || !$array)测试一个空数组。
Yes, we should expect an empty array, but we shouldn't expect a good implementation on functions without enforced return types.
是的,我们应该期望一个空数组,但我们不应该期望在没有强制返回类型的函数上有一个好的实现。
Examples with count()
例子 count()
var_dump(count(0));
> int(1)
var_dump(count(false));
> int(1)
回答by trante
Sometimes using empty is a must. For example this code:
有时使用空是必须的。例如这段代码:
$myarray = array();
echo "myarray:"; var_dump($myarray); echo "<br>";
echo "case1 count: ".count($myarray)."<br>";
echo "case1 empty: ".empty($myarray)."<br>";
$glob = glob('sdfsdfdsf.txt');
echo "glob:"; var_dump($glob); echo "<br>";
echo "case2 count: ".count($glob)."<br>";
echo "case2 empty: ".empty($glob);
If you run this code like this: http://phpfiddle.org/main/code/g9x-uwi
如果您像这样运行此代码:http: //phpfiddle.org/main/code/g9x-uwi
You get this output:
你得到这个输出:
myarray:array(0) { }
case1 count: 0
case1 empty: 1
glob:bool(false)
case2 count: 1
case2 empty: 1
So if you countthe empty glob output you get wrong output. You should check for emptiness.
因此,如果您count使用空的 glob 输出,则会得到错误的输出。你应该检查空性。
From globdocumentation:
从glob文档:
Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
Note: On some systems it is impossible to distinguish between empty match and an error.
返回一个包含匹配文件/目录的数组,如果没有文件匹配,则返回一个空数组,或者错误时返回 FALSE。
注意:在某些系统上,无法区分空匹配和错误。
Also check this question: Why count(false) return 1?
还要检查这个问题: Why count(false) return 1?

