user843939
user843939

Reputation:

php - fgets - read first line twice?

i have a while loop that FGETS through an external file and then executes function a() over each line.

what i want to do is to first look at the first line. if the line meets certain criteria, I want to execute function b() with it and then have the while loop work the a() function over lines 2+.

if the first line does NOT match the criteria, then i want the while loop to work the a() function over lines 1+.

is this possible without having to close and reopen the file again?

Upvotes: 1

Views: 1772

Answers (3)

RiaD
RiaD

Reputation: 47619

After you read first line you can reset file pointer to start of file, using fseek

fseek($file,0);

Upvotes: 3

Billy Moon
Billy Moon

Reputation: 58521

If the file is not too big to be read into memory, you can just use file() instead of FGETS like this

$lines = file('the-data.file');
foreach($lines as $line){
 if (meets_criteria($line))
  {
    b($line);
    a(implode(array_slice($lines,2)));
  }
  else
  {
    a(implode($lines));
  };
};

Upvotes: -1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798546

Absolutely. Here's one way:

if (($line = fgets(...)) !== false)
{
  if (meets_criteria($line))
  {
    b($line);
  }
  else
  {
    a($line);
  };
  while (($line = fgets(...)) !== false)
  {
    a($line);
  };
};

Feel free to fix any errors found.

Upvotes: 0

Related Questions