Checking for empty arrays: count vs empty

前端 未结 12 772
隐瞒了意图╮
隐瞒了意图╮ 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:43

    count() seems to work better with array-like interfaces that implement ArrayAccess/Countable. empty() returns true for these kinds of objects even if they have no elements. Typically these classes will implement the Countable interface, so if the question is "Does this collection contain elements?" without making an assumption about the implementation, then count() is a better option.

提交回复
热议问题