【问题标题】:Breaking a long PHP **for** statement into multiple lines将较长的 PHP **for** 语句分成多行
【发布时间】:2020-09-26 19:08:58
【问题描述】:

在 PHP 中 for 循环以

开头
for (init counter; test counter; increment counter)

这可以形成一条很长的线。
将其分解成较短部分的最佳方法是什么?

示例:

for ($currentLine = fgets ($fileToAnalyse); ! preg_match("^0 @Individual ", $currentLine); $currentLine = fgets($fileToAnalyse)) {/*...*/}

【问题讨论】:

    标签: php for-loop long-lines


    【解决方案1】:

    我认为对于特定示例,您使用了错误的循环。您不知道需要迭代多少次,因此,正确的循环是while。太长的行也不会有问题。

    $currentLine = fgets($fileToAnalyse);
    
    while(!preg_match("^0 @Individual ", $currentLine)) {
        // code...
        $currentLine = fgets($fileToAnalyse);
    }
    

    通常使用 for 循环,您几乎不会得到很长的行,因为它最常用于已知次数的明确迭代。

    但一般而言,要缩短 for 循环,您可以做一些奇怪的事情,例如在第一行之外导出变量的定义(我不推荐),例如:

    $currentLine = fgets ($fileToAnalyse);
    for (;! preg_match("^0 @Individual ", $currentLine);) {
        /*...*/
         $currentLine = fgets($fileToAnalyse)
    }
    

    【讨论】:

    • 您的回答是否意味着拆分 for 是不可能的? (也许我的例子不够深思熟虑;)
    • @mja 很好,第二个片段显示了一种缩短 for 循环的方法。除非我不明白这个问题?
    猜你喜欢
    • 1970-01-01
    • 2010-12-17
    • 2017-02-06
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多