Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the most efficient way to get and remove first line in file?

Tags:

file

php

I have a script which, each time is called, gets the first line of a file. Each line is known to be exactly of the same length (32 alphanumeric chars) and terminates with "\r\n". After getting the first line, the script removes it.

This is done in this way:

$contents = file_get_contents($file));
$first_line = substr($contents, 0, 32);
file_put_contents($file, substr($contents, 32 + 2)); //+2 because we remove also the \r\n

Obviously it works, but I was wondering whether there is a smarter (or more efficient) way to do this?

In my simple solution I basically read and rewrite the entire file just to take and remove the first line.

like image 834
Marco Demaio Avatar asked Mar 08 '10 21:03

Marco Demaio


2 Answers

I came up with this idea yesterday:

function read_and_delete_first_line($filename) {
  $file = file($filename);
  $output = $file[0];
  unset($file[0]);
  file_put_contents($filename, $file);
  return $output;
}
like image 83
Daniel Avatar answered Oct 05 '22 12:10

Daniel


There is no more efficient way to do this other than rewriting the file.

like image 14
Byron Whitlock Avatar answered Oct 05 '22 11:10

Byron Whitlock