IT story

빈 배열 확인 : 개수 대 비어 있음

hot-time 2020. 8. 26. 19:24
반응형

빈 배열 확인 : 개수 대 비어 있음


' PHP 배열이 비어 있는지 확인하는 방법 '에 대한이 질문은이 질문에 대해 생각했습니다.

배열이 비어 있는지 여부를 결정할 때 count대신 사용해야 하는 이유가 empty있습니까?

내 개인적인 생각은 empty부울 질문에 부울 답변을 제공 하기 때문에 사용해야하는 빈 배열의 경우 2가 동일하다면 것 입니다. 위에 링크 된 질문에서 그것이 count($var) == 0대중적인 방법 인 것 같습니다 . 나에게는 기술적으로 정확하지만 말이되지 않습니다. : $ var, 비어 있습니까? A : 7 . 흠 ...

count == 0대신 사용해야하는 이유가 있습니까 아니면 개인적인 취향의 문제입니까?

지금 삭제 된 답변에 대한 주석에서 다른 사람들이 지적 count했듯이은 모든 요소를 ​​계산해야하기 때문에 큰 배열의 성능에 영향을 미치는 반면 empty비어 있지 않다는 것을 알게되는 즉시 중지 할 수 있습니다. 따라서이 경우 동일한 결과를 제공하지만 count잠재적으로 비효율적이라면 왜 우리는 count($var) == 0?


나는 일반적으로 empty. 사람들이 실제로 count를 사용하는 이유를 모르겠습니다. 배열이 크면 count가 더 오래 걸리거나 오버 헤드가 더 많습니다. 배열이 비어 있는지 여부를 알 필요가 있다면 empty를 사용하십시오.


어떤 것이 실제로 더 빠른지 궁금해서 이러한 기능을 벤치마킹하는 간단한 스크립트를 만들었습니다.

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

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


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.


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


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.


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
}

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


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.


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?


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.


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)

참고URL : https://stackoverflow.com/questions/2216110/checking-for-empty-arrays-count-vs-empty

반응형