0

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 ?

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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.

Comments

0

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.

2 Comments

!empty($arr) will also return true if $arr is not an array (for instance an integer 1)
Indeed, not empty is not ideal either. +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.