Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

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

11:33 pm on Sep 27, 2009 (gmt 0)

Junior Member

10+ Year Member

joined:Sept 26, 2005
votes: 0

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:


read all lines except the last one? In the previous example I need to hold only AAAA, BBBB , CCCC and DDDD.
Thank you!
1:30 am on Sept 28, 2009 (gmt 0)

Senior Member

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Nov 28, 2004
votes: 0

There may be a function for this, but I'd just store the lines in an array and use array_pop to remove the last item of the array, then overwrite the file.

array_shift [us3.php.net] removes the first item, array_pop [us3.php.net] the last, array_splice [us3.php.net] to remove items within the array.

A side note, all these return the removed items, so if you want to do anything with them, you can.

$removed = array_pop($line_array);

9:55 pm on Sept 28, 2009 (gmt 0)

Senior Member

WebmasterWorld Senior Member 5+ Year Member

joined:June 10, 2008
posts: 1130
votes: 0

I didn't test this but I'm pretty sure it's close. I used to write a lot of text files
//the path of your file
$fileName = "temp.txt";

//all of the lines
$fileArray = file($fileName);

//open the file for overwriting
$handle = fopen($fileName, "w");

//now write all of the lines except the last one
//that was removed from the array
foreach($fileArray as $i){

//if this doesn't work print some error
if(!(fwrite($handle, $i."\n"))){

echo("there was some error in writing the line $i");

}//if !(fwrite)