Php judges that an array is null if (! Array (), or if (empty (array ()))? Php judges that an array is null if (! Array (), or if (empty (array ()))?
Reply content: php determines if (! Array (), or if (empty (array ()))?
First habitually, RTFM
No, it's okay. It's not suitable.
!
Andempty()
What are the differences between behaviors?
!
Returns the inverse value after being converted to a Boolean value. For the result, refer to the Boolean value conversion section in the manual.
empty
See the manual for the same behavior.
There are three differences in their behaviors.
Empty SimpleXML (after experiment, it is found that this is a document problem. After php5.1, the behavior of both is consistent)
Undefined variables (!$undefined
An error occurs,empty($undefined)
Returns true) andisset
Similarly, this feature is especially friendly for accessing arrays or object members with complex structures (empty($arr['userModel']->userFriends)
)
Before php5.5,empty
Only variables are accepted, and expressions are not accepted (such as the returned results of Functions ).empty(getSomething())
)
Some people also mentioned in the comments that, because empty is a language structure and does not have the huge overhead of function calls, the performance difference between the two will not be too great, in addition, modern PHP has been optimized for this small overhead, so we do not need to consider performance here. Based on the above analysis,empty
Yes is better!
Unless your php version is old, but you need to directly judge the expression, do not want to add a variable
However, if you do not know whether the items in your hand are arrays, we suggest you refer to @ dreamans's answer to consider$arr
Not suitable for Array scenarios.
Becauseis_array
Does not haveempty
Can tolerate undefined features. I recommend this method.empty($arr) && is_array($arr)
Able to strictly support various scenarios
If (empty ($ undefined) & is_array ($ undefined); // if (empty ($ arr ['usermodel']-> userFriends) & is_array ($ arr ['usermodel']-> userFriends); // (potential) undefined member // or reverse scenario, to determine whether a content array exists, combined with the ability of expressions if (! Empty ($ things = getSomething () & is_array ($ things ));
Of course, a better style is replaced by typehinting.is_array
It must be an array and must have been defined. The situation is much better.
The description of empty behaviors in the official manual is incomplete. I have already commented on it. Please help us with upvote.
If (count ($ arr) {// The array is not empty}
Identical results
Code writing should be rigorous:
if(is_array($arr) && !$arr) { do something}
The answer is written in the comment.