Checking for empty arrays: count vs empty

前端 未结 12 699
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 12:59

This question on \'How to tell if a PHP array is empty\' had me thinking of this question

Is there a reason that count should be used instead of e

12条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 13:54

    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)
    

提交回复
热议问题