duanlei7101 2010-08-02 19:17
浏览 20
已采纳

什么是验证元素是否已准备好在php中的foreach()循环中使用的最佳方法?

example:

foreach($boxes as $box) {
    echo "$box 
";
}

Used to be fairly easy, I could just wrap the foreach around a check like:

if(is_array($boxes) && count($boxes) > 0) {
    //foreach loop here
}

Without having to worry about a warning getting thrown if for whatever reason bad input was passed to the $boxes array.

When Iterators, were added to the mix, this no longer works, as Iteratable objects are not arrays. So, I have a few solutions, but am wondering if there is a 'best practice' for this.

// 1:
if($boxes instanceof Traversable && count($boxes) > 0) {
    //foreach loop here
}

// 2:
if($boxes && count($boxes) > 0) {
    //foreach loops here
}

There are others, but these seem like the most obvious. Anyone have any suggestions. PHP docs seem to be silent.

  • 写回答

5条回答 默认 最新

  • dtziv24262 2010-08-02 19:23
    关注

    You shouldn't have the count($array) > 0 part, because a) foreach works fine with empty arrays, b) objects can be Traversable yet not be Countable and c) the value returned by count() may even (for objects) be disconnected from the number of items the traversal will yield.

    And #1 there is different from #2; since $boxes instanceOf Traversable is not the same as $boxes. Also note that internally arrays don't implement Traversable.

    I would go with

    if (is_array($boxes) || $boxes instanceof Traversable) {
        foreach (...)
    }
    

    This still doesn't guarantee that the traversal will be successful; the iteration may throw an exception at any point. In particular, for some classes it may not make sense to traverse them more than once.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀