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 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波