homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

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

 11:33 pm on Sep 27, 2009 (gmt 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 Sep 28, 2009 (gmt 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 Sep 28, 2009 (gmt 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)

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved