Adam
Adam

Reputation: 1159

PHP Loop - skip certain lines

I have a very large text file with over 100,000 lines in it. I need to collect/skip a set number of lines: loop through lines 1-100, skip lines 101-150, read lines 151-210, skip lines 211-300 (for example).

I have the following code

$lines = file('file.txt');
$counter = 0;

foreach ($lines as $lineNumber => $line) {

    $counter++;

    if ($counter < 101) {
         //Do update stuff
    }

    if ($counter < 102 && $counter > 151) {
         //Skip these lines
    }

    if ($counter < 152 && $counter > 211) {
         //Do update stuff
    } 
}

Is there a better way to skip over many lines of an array's output?

Upvotes: 0

Views: 577

Answers (1)

shukshin.ivan
shukshin.ivan

Reputation: 11340

First, move to fgets, it is memory efficient way. You don't need to have all the array in memory. As for conditions, just combine all your conditions with or operator and don't add condition for skipping, it's useless.

if ($counter < 101 || ($counter >= 151 && $counter <= 210) || add another pediods here) {
     //Do update stuff
}

P.S. you have a mistake in your conditions, ($counter < 102 && $counter > 151) is always false as well as the other one.

Upvotes: 2

Related Questions