PHP determines if an array is empty if (!array ()) Good, or if (empty (array ()))?
Reply content:
PHP determines if an array is empty if (!array ()) Good, or if (empty (array ()))?
First, habitually, RTFM.
No, it's not right.
!
empty()
What's the difference between a behavior?
!
Equivalent to converting to a Boolean value after inversion, the result can refer to the manual of the Boolean conversion section
empty
Behavior is also shown in the manual
There are 3 differences in their behavior.
Empty simplexml (after experiments, found that this is a document problem, after php5.1, the behavior is consistent)
Undefined variables (which !$undefined
will produce error, empty($undefined)
return true) and isset
similar, this feature is particularly friendly when accessing arrays or object members of complex structures ( empty($arr['userModel']->userFriends)
)
Before php5.5, empty
only accept the variable, do not accept the expression (such as the return result of the function empty(getSomething())
)
It is also said in the comments, because empty is a language structure, and there is no significant overhead of function calls, so the performance of the two differences will not be too large, and modern PHP for this small overhead has been optimized, so there is little need to consider performance. Combined with the above analysis, empty
is better than !
, unless your PHP version is older, but also need to directly judge the expression, do not want to add a variable
However, if you do not know what is in your hand is not an array, it is recommended to refer to the @dreamans answer, consider $arr
not an array of scenarios to do appropriate processing.
Since there is no is_array
empty
tolerance for undefined features, I recommend this notationempty($arr) && is_array($arr)
Able to rigorously support a variety of scenarios
if(empty($undefined) && is_array($undefined));//未定义变量if(empty($arr['userModel']->userFriends) && is_array($arr['userModel']->userFriends));//(潜在)未定义成员//或者反向场景,判断有内容数组,结合表达式的能力if(!empty($things = getSomething()) && is_array($things));
Of course, the better style is to use typehinting instead is_array
, must be an array and must have defined, the situation is much better
The description of empty in the official manual is incomplete, has been added to the comments, you are free to help upvote
if (count($arr)) { // 数组不为空}
The effect is exactly the same
Write code to be rigorous:
if(is_array($arr) && !$arr) { do something}
The answer is written in the comments.