PHP: Most efficient way to remove the first line from a file

Posted on 2011-10-11
Last Modified: 2012-08-13
Using PHP. what is the most efficient way to remove the first line from a text file?
Question by:hankknight
    LVL 13

    Assisted Solution

    by:Hugh McCurdy
    I don't know of a way except to read each line from the file and write lines 2 through n to a different file followed by delete and rename.

    Perhaps someone else has some magic but I'd be surprised.
    LVL 107

    Assisted Solution

    by:Ray Paseur
    The most efficient way would be to not create the first line at all.  So modifying the code that creates the file might be one good option

    But if it is already there, then the process would be what hmccurdy described.  You might want to take a backup before you start since this is an irrevocable change in the file system.  You would also want to be sure you did not accidentally rerun this process.  That argues for a separate directory to hold the new files.

    Pidgin code:

    while (!feof){
    unlink old
    rename new

    If the files are relatively small and will fit in memory, you can use file() to read the file into an array.

    $arr = file(path/to/file)
    $str = implode(PHP_EOL, $arr)
    LVL 13

    Expert Comment

    by:Hugh McCurdy
    Good point, Ray.

    Just occurred to me that it might be a CSV file.  Is it a CSV file?
    LVL 20

    Accepted Solution


    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    A colleague recently asked me about how to give his client a small part of the web site that could be completely under the client's control.  Since I have done this sort of thing before to add emergency banners to a web site, I decided I would creat…
    Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit ( and similar technologies have enjoyed wide adoption, making it possib…
    The viewer will learn how to count occurrences of each item in an array.
    This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

    733 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now