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!

Link to comment
Share on other sites

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);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.