Read random text from txt file (fread?)

Discussion in 'PHP' started by Kerosene, Dec 21, 2006.

  1. #1
    How can I use fread (or something similar) to grab a random word from a txt file?

    The txt file is a list of words separated by commas. e.g.

    "apple,banana,fish,bones,orange,grapefruit" etc...

    If it makes things easier, I can change the comma delimiter in the text file to something else.
     
    Kerosene, Dec 21, 2006 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    
    $words = expode(',', file_get_contents('your-text-file.txt'));
    $word = trim($words[array_rand($words)]);
    
    echo $word;
    
    
    PHP:
    Untested.
     
    nico_swd, Dec 22, 2006 IP
  3. Kerosene

    Kerosene Alpha & Omega™ Staff

    Messages:
    11,366
    Likes Received:
    575
    Best Answers:
    4
    Trophy Points:
    385
    #3
    Works perfectly - thank you!

    All I had to do was put the missing "L" in explode :D
     
    Kerosene, Dec 22, 2006 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    Lol, sorry... typo. Glad it works though. :D
     
    nico_swd, Dec 22, 2006 IP
    Kerosene likes this.