Question about pulling random items

Discussion in 'PHP' started by jokershouse, Sep 6, 2007.

  1. #1
    I'm trying to pull a random number of keywords from a file...and I just can get it. Basically what I have is a list of keywords, on per line, in a text file, and I need to pull out x number of those keywords on the fly. I don't have access to a database, hence the text file.

    So what I have so far is:

    
    <?
    $f1 = file("keywords.txt");
    $max = "10";
    $min = "5";
    $item = array_rand ($f1);
    $toshow = rand($max,$min);
    $i = 1;
    while ($i < $toshow){
    
    echo $item[$i];
    
    $i = $i+1;
    
    };
    ?>
    
    Code (markup):
    But obviously this isn't working or I wouldn't be here... Any help?

    Thanks in advance,

    Mike
     
    jokershouse, Sep 6, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Use array_rand(). It's much easier and you can specify the number of items you want to pull.
     
    nico_swd, Sep 6, 2007 IP
  3. jokershouse

    jokershouse Peon

    Messages:
    155
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Is it possible that you could give me an example...I really seem to be struggling with this. thanks in advance, Mike
     
    jokershouse, Sep 6, 2007 IP
  4. xemiterx

    xemiterx Peon

    Messages:
    62
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Displays between 2 and 6 random lines from test.txt:

    $keyword_array = file('test.txt');
    
    $min = 2;
    
    $max = 6;
    
    $num_keywords = rand($min, $max);
    
    $rand_keyword_keys = array_rand($keyword_array, $num_keywords);
    
    foreach ($rand_keyword_keys as $key => $value) {
    	echo $keyword_array[$value] . '<br />';		
    }
    PHP:
     
    xemiterx, Sep 6, 2007 IP
    jokershouse likes this.