检查空数组:计数与空数组

发布于 2024-08-20 17:12:36 字数 679 浏览 9 评论 0原文

这个问题关于'如何判断 PHP array isempty' 让我想到了这个问题

在确定数组是否为空时,是否有理由使用 count 而不是 empty

我个人的想法是,如果 2 对于空数组的情况是等效的,您应该使用 empty 因为它为布尔问题提供了布尔答案。从上面链接的问题来看,似乎 count($var) == 0 是流行的方法。对我来说,虽然技术上是正确的,但毫无意义。例如问:$var,你是空的吗?答:7。嗯...

我是否应该使用 count == 0 来代替,或者只是个人品味问题?

正如其他人在现已删除的答案的评论中指出的那样, count 将对大型数组产生性能影响,因为它必须计算所有元素,而 empty 可以立即停止因为它知道它不是空的。因此,如果在这种情况下它们给出相同的结果,但 count 可能效率低下,那么我们为什么要使用 count($var) == 0 呢?

This question on 'How to tell if a PHP array is empty' had me thinking of this question

Is there a reason that count should be used instead of empty when determining if an array is empty or not?

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...

Is there a reason I should use count == 0 instead or just a matter of personal taste?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

影子是时光的心 2024-08-27 17:12:36

我通常使用。我不确定为什么人们会真正使用 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.

心在旅行 2024-08-27 17:12:36

我很好奇哪一个实际上更快,因此我制作了一个简单的脚本来对这些函数进行基准测试。

<?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

由于我正在这样做,所以我还尝试检查通常与 count()/empty() 相关的操作的性能

使用 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

使用 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

结论,如果您是使用 PHP:

  1. empty() 在这两种情况下都比 count() 快得多,使用空数组和填充数组

  2. count() 对满数组或空数组执行相同的操作。

  3. 进行简单的 IF 或仅进行布尔运算是相同的。

  4. IF/ELSE 的效率比 (?:) 稍高。除非您使用中间的表达式进行数十亿次迭代,否则它完全无关紧要。

如果您使用 HHVM,结论是:

  1. empty() 比 count() 快一点点,但并不明显。

    [其余部分与 PHP 中的相同]

总而言之,如果您只需要知道数组是否为空,请始终使用empty();

这只是一个奇怪的测试,只是在没有考虑很多事情的情况下完成的。它只是一个概念证明,可能无法反映生产中的操作。

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()

Using 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)

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:

  1. empty() is much much faster than count() in both scenarios, with an empty and populated array

  2. count() performs the same with a full or empty array.

  3. Doing a simple IF or just a Boolean operation is the same.

  4. IF/ELSE is very slightly more efficient than ( ? : ). Unless you're doing billions of iterations with expressions in the middle it is completely insignificant.

Conclusions if you're using HHVM:

  1. empty() is a teeny-weeny bit faster than count() but insignificantly so.

    [ The rest is the same as in PHP ]

In conclusion of the conclusion, if you just need to know if the array is empty always use 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.

陪我终i 2024-08-27 17:12:36

我认为这只是个人喜好。有些人可能会说 empty 更快(例如 http://jamessocol.com/projects /count_vs_empty.php),而其他人可能会说 count 更好,因为它最初是为数组创建的。 empty 更通用,可以应用于其他类型。

php.net 对于 count 给出以下警告:

count() 可能会为未设置的变量返回 0,但也可能为已使用空数组初始化的变量返回 0。使用 isset() 测试变量是否已设置。

换句话说,如果未设置该变量,您将收到 PHP 的通知,指出该变量未定义。因此,在使用 count 之前,最好使用 isset 检查变量。对于empty 来说,这不是必需的。

I think it's only personal preference. Some people might say empty is faster (e.g. http://jamessocol.com/projects/count_vs_empty.php) while others might say count is better since it was originally made for arrays. empty is more general and can be applied to other types.

php.net gives the following warning for count though :

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.

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.

溺渁∝ 2024-08-27 17:12:36

在确定数组是否为空时,是否应该使用 count 而不是空?

有,当您需要在知道其大小的非空数组上执行某些操作时:

if( 0 < ( $cnt = count($array) ) )
{
 echo "Your array size is: $cnt";
}
else
 echo "Too bad, your array is empty :(";

但我不建议使用 count ,除非您 100% 确定您正在计算的是一个数组。最近我一直在调试代码,其中错误函数返回 FALSE 而不是空数组,我发现的是:

var_dump(count(FALSE));

输出:

int 1

所以从那时起我使用 empty 或 < code>if(array() === $array) 以确保我的 array 是空的。

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 FALSE instead of empty array, and what I discovered was:

var_dump(count(FALSE));

output:

int 1

So since then I am using empty or if(array() === $array) to be sure that I have array that is empty.

策马西风 2024-08-27 17:12:36

count() 似乎与实现 ArrayAccess/Countable 的类数组接口配合得更好。对于这些类型的对象,即使它们没有元素,empty() 也会返回 false。通常,这些类将实现 Countable 接口,因此如果问题是“此集合是否包含元素?”如果不对实现做出假设,那么 count() 是一个更好的选择。

count() seems to work better with array-like interfaces that implement ArrayAccess/Countable. empty() returns false for these kinds of objects even if they have no elements. Typically these classes will implement the Countable interface, so if the question is "Does this collection contain elements?" without making an assumption about the implementation, then count() is a better option.

深巷少女 2024-08-27 17:12:36

或者,您可以将变量转换为布尔值(隐式或显式):

if( $value )
{
  // array is not empty
}

if( (bool) $value )
{
  // array is still not empty
}

如果未定义变量,此方法会生成 E_NOTICE,类似于 count()

有关详细信息,请参阅有关类型比较的 PHP 手册页面

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_NOTICE if the variable is not defined, similarly to count().

For more information, see the PHP Manual page on type comparisons.

童话里做英雄 2024-08-27 17:12:36

没有充分的理由选择 count($myArray) == 0 而不是 empty($myArray)。它们具有相同的语义。有些人可能会发现其中一个比另一个更具可读性。其中一个的性能可能比另一个稍好一些,但它不太可能成为绝大多数 php 应用程序中的重要因素。出于所有实际目的,选择取决于品味。

There is no strong reason to prefer count($myArray) == 0 over empty($myArray). They have identical semantics. Some might find one more readable than the other. One might perform marginally better than the other but it's not likely to be a significant factor in the vast majority of php applications. For all practical purposes, the choice is a matter of taste.

世界如花海般美丽 2024-08-27 17:12:36

我个人更喜欢编码优雅(与我的具体用例相关)。我同意 Dan McG 的观点,因为 count() 没有以正确的数据类型(在本例中为布尔值)响应相关测试,迫使开发人员编写更多代码来填充“if”语句。

这是否对性能有任何重大影响只有对于非常大的数组才有争议(在大多数设置中你可能不会有足够的内存分配)。

特别是当涉及到 PHP 的 $_POST 数组时,我认为编写/查看似乎更“合乎逻辑”:

if ( !empty ( $_POST ) ) {
    // deal with postdata
}

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.

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:

if ( !empty ( $_POST ) ) {
    // deal with postdata
}
静谧 2024-08-27 17:12:36

希望这可以帮助某人,即使它已经得到回答(并争论了一些什么)。在我自己的场景中,我知道我的所有数组都有 7 个元素(在我的代码中之前进行了检查),并且我正在执行一个 array_diff ,它当然会在相等时返回一个为零的数组。

我有 34 秒的时间来计数,17 秒的时间为空。两者都给了我相同的计算,所以我的代码仍然没问题。

但是,您也可以尝试 =====,如 PHP - 检查两个数组是否相等。我想说的最好的方法是尝试 countempty== 空数组,然后看看哪个能提供您自己的最佳性能。就我而言,count 是最慢的,所以我现在使用empty...接下来将检查serialize

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_diff which of course returns an array of zero when equal.

I had 34 sec for count and 17 sec for empty. Both give me the same calculations so my code is still fine.

However you can also try the == or === as in PHP - Check if two arrays are equal. The best I would say is try count vs empty vs == empty array, then see which gives your own best perfs. In my case count was the slowest so I am using empty now... will be checking serialize next

辞旧 2024-08-27 17:12:36

有时使用空是必须的。例如此代码:

$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);

如果您像这样运行此代码: http://phpfiddle.org/main /code/g9x-uwi

你会得到这样的输出:

myarray:array(0) { } 
case1 count: 0
case1 empty: 1

glob:bool(false) 
case2 count: 1
case2 empty: 1

因此,如果你计算空的 glob 输出,你会得到错误的输出。您应该检查是否为空。

来自 glob 文档:

返回一个包含匹配文件/目录的数组,一个空的
如果没有文件匹配则为数组,否则错误为 FALSE。
注意:在某些系统上
无法区分空匹配和错误。

另请检查这个问题:
为什么 count(false) 返回 1?

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

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 count the empty glob output you get wrong output. You should check for emptiness.

From glob documentation:

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.

Also check this question:
Why count(false) return 1?

三生池水覆流年 2024-08-27 17:12:36

由于解析为负数的变量将返回 int(1)count()

我更喜欢 ($array === [] || !$array)< /code> 测试空数组。

是的,我们应该期望一个空数组,但是我们不应该期望在没有强制返回类型的情况下函数能够得到良好的实现。

count() 的示例

var_dump(count(0));
> int(1)
var_dump(count(false));
> int(1)

Since a variable parsed as negative would return int(1) with count()

I prefer ($array === [] || !$array) to test for an empty 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()

var_dump(count(0));
> int(1)
var_dump(count(false));
> int(1)
三月梨花 2024-08-27 17:12:36

我改变了主意,谢谢。

好的,emptycount 的用法没有区别。从技术上讲,count 应该用于数组,empty 可以用于数组和字符串。因此,在大多数情况下,它们是可以互换的,如果您查看 php 文档,如果您处于 empty 状态,您将看到 count 的建议列表,反之亦然。

I remade my mind guys, thanks.

Ok, there is no difference between the usage of empty and count. Technically, count should be used for arrays, and empty could be used for arrays as well as strings. So in most cases, they are interchangeable and if you see the php docs, you will see the suggestion list of count if you are at empty and vice versa.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文