检查空数组:计数与空 [英] Checking for empty arrays: count vs empty
问题描述
这个问题关于'如何分辨如果 PHP 数组为空'让我想到了这个问题
This question on 'How to tell if a PHP array is empty' had me thinking of this question
在确定数组是否为空时,是否有理由使用 count
而不是 empty
?
Is there a reason that count
should be used instead of empty
when determining if an array is empty or not?
我个人的想法是,如果 2 等价于空数组的情况,您应该使用 empty
因为它为布尔问题提供了布尔答案.从上面链接的问题来看,似乎 count($var) == 0
是流行的方法.对我来说,虽然技术上是正确的,但毫无意义.例如.问:$var,你是空的吗?答:7.嗯……
My personal thought would be if the 2 are equivalent for the case of empty arrays you should use empty
because it gives a boolean answer to a boolean question. From the question linked above, it seems that count($var) == 0
is the popular method. To me, while technically correct, makes no sense. E.g. Q: $var, are you empty? A: 7. Hmmm...
是否有理由我应该使用 count == 0
而不是个人喜好?
Is there a reason I should use count == 0
instead or just a matter of personal taste?
正如其他人在对现已删除的答案的评论中指出的那样,count
将对大型数组的性能产生影响,因为它必须计算所有元素,而 empty
可以一旦它知道它不是空的就停止.所以,如果他们在这种情况下给出相同的结果,但 count
可能效率低下,我们为什么要使用 count($var) == 0
?
As pointed out by others in comments for a now deleted answer, count
will have performance impacts for large arrays because it will have to count all elements, whereas empty
can stop as soon as it knows it isn't empty. So, if they give the same results in this case, but count
is potentially inefficient, why would we ever use count($var) == 0
?
推荐答案
我一般使用 empty
.我不知道为什么人们真的会使用 count - 如果数组很大,那么 count 需要更长的时间/有更多的开销.如果您只需要知道数组是否为空,则使用empty.
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.
这篇关于检查空数组:计数与空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!