steve
steve

Reputation: 586

Testing an array is empty in a if statement

i used this way to testing an array $arr if empty

if(!empty($arr)){ //do something }

recently, i saw someone use an another like:

if($arr){ //do something }

just want to know is't the second way a simply way to testing an array or is there some potential risk here ?

Upvotes: 0

Views: 1426

Answers (4)

Aaron
Aaron

Reputation: 4614

The second way is not ideal. If you use the second method and determine you're dealing with an array (and you aren't) and pass it to a foreach statement, you'll end up with an error. It is also more instructive for what you're checking to do more than test with if($arr).

My preference is:

if (is_array($arr) && count($arr) > 0) {
    //work with array
}

Edit: I think my underlying point here is that the ability to test an array's existence is only part of the problem. If $arr turns out to be a string, a more robust check is needed.

Upvotes: 0

David Z.
David Z.

Reputation: 5701

Both methods are functionally equivalent. The documentation for empty() mentions the following things are considered to be empty

"", 0, 0.0, "0", NULL, FALSE, array(), var $var; 

Taking a look at casting to a bool, we can see that the list matches the list, which means both methods handle different types in the same way.

Upvotes: 1

deceze
deceze

Reputation: 522110

An empty array like array() is regarded as equal to false. So a simple if ($arr) works perfectly fine.

empty does the same kind of comparison, but does not trigger a NOTICE about missing variables, should the variable $arr not exist at all. You should not use empty if you are sure the variable exists, since it suppresses valuable error reporting. Only use empty if you really don't know whether a variable exists or not and have no control over it.

For more information about empty see The Definitive Guide To PHP's isset And empty.

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

The second casts the array to a boolean. Empty arrays are cast to false, anything else to true. So if($arr) and if(!empty($arr)) are functionally identical.

Upvotes: 3

Related Questions