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

前端 未结 12 2249
天命终不由人
天命终不由人 2020-12-03 03:53

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 \"

12条回答
  •  -上瘾入骨i
    2020-12-03 04:03

    Here's one way:

    $contents = file($file, FILE_IGNORE_NEW_LINES);
    $first_line = array_shift($contents);
    file_put_contents($file, implode("\r\n", $contents));
    

    There's countless other ways to do that also, but all the methods would involve separating the first line somehow and saving the rest. You cannot avoid rewriting the whole file. An alternative take:

    list($first_line, $contents) = explode("\r\n", file_get_contents($file), 2);
    file_put_contents($file, implode("\r\n", $contents));
    

提交回复
热议问题