Jump to content

Remove last line in a file PHP/Store all lines except the last one


ktsirig

Recommended Posts

Hello all! Is there a way to remove the last line in a text file? Or, alternatively, is there a way to read a text file until the penultimate line of the file?

That is, if you have a file like:

AAAA
BBBB
CCCC
DDDD
XXXXXXXX

read all lines except the last one? In the previous example I need to hold only AAAA, BBBB , CCCC and DDDD.

Thank you!

If you use file() you can get all the data of a file into an array (each line has it's own element). Then using array_pop() you can remove the last element from that array. Finally if you want the contents of the file in a string rather than an array use implode().

 

$file = file('somefile.txt');
array_pop($file);
$content = implode("\n", $file);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.