phpfor-looplong-lines

Breaking a long PHP **for** statement into multiple lines


In PHP for loop starts with

for (init counter; test counter; increment counter)

which can form quite a long line.
What is the best way to break it into shorter parts?

Example:

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

Solution

  • I think for the specific example you are using the wrong loop. You do not know how many times you will need to iterate, therefore, the right loop would be while. You would not have a problem with too long line either.

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

    Typically with for loop you should hardly ever get very long lines, since it is most often used with definite iteration for a known number of times.

    But to shorten the for loop in general, you could do some weird stuff like exporting the definition of variable outside of the first line (which I would not recommend) like:

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