1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

display random line from text file then delete line

Discussion in 'PHP & Perl' started by specopkirbs, Feb 25, 2012.

  1. specopkirbs

    specopkirbs BANNED BANNED

    Joined:
    Nov 28, 2008
    Messages:
    920
    Likes Received:
    746
    im looking for the php code to display random line from text file and then delete that line from the text file
    any help would be appreciated happy to pay
     
  2. jazzc

    jazzc Moderator Staff Member Moderator Jr. VIP

    Joined:
    Jan 27, 2009
    Messages:
    2,468
    Likes Received:
    10,147
    If it 's not a huge file, something like this should work

    Code:
    $file = "foo.txt";
    
    $lines = file($file);
    
    $line = mt_rand(0,count($lines)-1);
    unset($lines[$line]);
    
    $fp = fopen($file, 'w+');
    
    foreach($lines as $line) {
        fwrite($fp,$line); 
    }
    
    fclose($fp);
    
     
    • Thanks Thanks x 1
  3. Enigma32

    Enigma32 Jr. VIP Jr. VIP Premium Member

    Joined:
    Aug 28, 2010
    Messages:
    210
    Likes Received:
    108
    you forgot to echo it
     
    • Thanks Thanks x 1
  4. specopkirbs

    specopkirbs BANNED BANNED

    Joined:
    Nov 28, 2008
    Messages:
    920
    Likes Received:
    746
    what bit do i echo lol sorry i have no clue when it comes to php
     
  5. Zak_A

    Zak_A Jr. VIP Jr. VIP Premium Member

    Joined:
    Mar 16, 2008
    Messages:
    808
    Likes Received:
    873
    Gender:
    Male
    Occupation:
    WP designer & developer
    Location:
    Western Europe
    With the echo bit added :)

    Code:
    $file = "foo.txt";
    
    $lines = file($file);
    
    $line = mt_rand(0,count($lines)-1);
    
    echo $lines[$line];
    
    unset($lines[$line]);
    
    $fp = fopen($file, 'w+');
    
    foreach($lines as $line) {
        fwrite($fp,$line); 
    }
    
    fclose($fp);
     
    • Thanks Thanks x 2