array_rand - bamboozling me!

Discussion in 'PHP' started by Kerosene, Nov 8, 2007.

  1. #1
    Now here's an easy one for the PHP gurus...

    $mywords = "cat,dog,apple,banana,giraffe,nintendo,guava";
    Code (markup):
    How can I create a new array, using 3 random values from $mywords?
    I'm guessing array_rand will come into play, but I just can't work it out...
     
    Kerosene, Nov 8, 2007 IP
  2. ndreamer

    ndreamer Guest

    Messages:
    339
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #2
    first thats a string you have there, you can't use array rand with out doing something like

    
    $mywords = "cat,dog,apple,banana,giraffe,nintendo,guava";
    $input = explode(',',$mywords);
    
    srand((float) microtime() * 10000000);
    $rand_keys = array_rand($input, 2);
    print_r($rand_keys);
    Code (markup):
    array_rand does not actually sort the array, it just returns some random keys to which can be used to pick random entry's from the array.
     
    ndreamer, Nov 8, 2007 IP
    Kerosene likes this.
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    Note that since PHP 4.2.0, you don't need to use srand() anymore.
     
    nico_swd, Nov 8, 2007 IP
  4. Kerosene

    Kerosene Alpha & Omega™ Staff

    Messages:
    11,366
    Likes Received:
    575
    Best Answers:
    4
    Trophy Points:
    385
    #4
    Sorry to be a complete dunce here... but
    $mywords = "cat,dog,apple,banana,giraffe,nintendo,guava";
    $input = explode(',',$mywords);
    $rand_keys = array_rand($input, 2);
    print_r($rand_keys);
    Code (markup):
    is printing
    Array ( [0] => 1 [1] => 2 )

    How can I make it output the actual words (e.g banana, guava etc)?
     
    Kerosene, Nov 8, 2007 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    
    $mywords = "cat,dog,apple,banana,giraffe,nintendo,guava";
    
    $words = explode(',', $mywords);
    $keys = array_rand($words, 3);
    
    foreach ($keys AS $key)
    {
    	echo $words[$key], ' ';
    }
    
    
    PHP:
     
    nico_swd, Nov 8, 2007 IP
  6. Kerosene

    Kerosene Alpha & Omega™ Staff

    Messages:
    11,366
    Likes Received:
    575
    Best Answers:
    4
    Trophy Points:
    385
    #6
    Thanks guys :)

    +Rep to you both.
     
    Kerosene, Nov 8, 2007 IP