duanqian8867 2015-11-13 15:41
浏览 13

为什么PHP for循环允许一组保护表达式?

A PHP for-loop is defined like so:

for (expr1; expr2; expr3)
    statement

Here expr1 and expr3 can also be a comma-separated list of expressions, which makes sense, e.g.,

for ($i = 0, $j = 1; $i < 3; $i++, $j++)
  echo $i, $j, PHP_EOL;

will output:

01
12
23

However, expr2 is also allowed to be a list of expressions, and it is not completely clear why this should be possible. For instance,

for ($i = 0, $j = 1; $i < 3, $j < 2; $i++, $j++)
  echo $i, $j, PHP_EOL;

outputs only

01

Testing around a little bit, it seems that when expr2 is a list of expressions, they are all evaluated, but only the return value of the last expression is used to decide whether to continue iterating.

Is there any realistic scenario where having a list of expressions as the loop's guard actually makes sense, i.e., is there any good reason that this is possible? Or is this more like an artefact of the language?

  • 写回答

1条回答 默认 最新

  • dputlf5431 2015-11-13 16:28
    关注

    I'm having a hard time thinking of a practical application for this but it does allow you to evaluate any expression before determining whether the loop has ended (a little like do ... while)

    So, for instance:

    function spaff($s) {
        echo "{$s}
    ";
    }
    

    for($i=0; $i<10; $i++) {
        spaff($i);
    }
    
    //outputs
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    

    Because $i is evaluated to be less than 10 in the loop before the spaff() function is called, it is only called for values of $i less than 10.


    However:

    for($j=0; spaff($j), $j<10; $j++) {
    
    }
    
    //outputs
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    

    In this case spaff($j) is evaluated before $j is checked to be less than 10, so it is called for every value of $j including 10.

    I suspect this is an artefact of the language - behavior inherited from C - but if anyone can think of a practical application for this behavior, I'd be interested to hear it.

    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程