Need a simple PHP code to select random element of an array

Discussion in 'Programming' started by poseidon, Apr 5, 2007.

  1. #1
    I am looking to rotate ads (not adsense code but some other javascript ads). There are 4 types of ads, so I am thinking of putting it in an array and than use random function to select one of them to display.

    Something like
    <?php
    arr[4];
    arr[0]="Code1";
    ...
    arr[3]="Code4";

    num=Rand(give a number from 0 to 3);
    echo $arr[num];
    ?>

    Any help ? :)
     
    poseidon, Apr 5, 2007 IP
  2. sea otter

    sea otter Peon

    Messages:
    250
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    0
    #2
    
    <?php
    
    $ads_array = array(
    	'Code1',
    	'Code2',
    	'Code3',
    	'Code4'
    );
    
    	$ad = $ads_array[array_rand($ads_array)];
    
    	echo "Your ad is: $ad.\n";
    ?>
    
    PHP:
     
    sea otter, Apr 5, 2007 IP
  3. poseidon

    poseidon Banned

    Messages:
    4,356
    Likes Received:
    246
    Best Answers:
    0
    Trophy Points:
    0
    #3
    thanks seo_otter , will test the code later and inform how it worked.

    I am sure the elemensts, ode1,code2 can be multiple lines...
     
    poseidon, Apr 6, 2007 IP
  4. sea otter

    sea otter Peon

    Messages:
    250
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Not sure what you mean exactly, or if you're asking if they can be multiple lines, but the answer is yes. Or more specifically, it doesn't matter :)

    I only used a different notation than you, but it does the exact same thing. You can still populate and print the array using your notation and naming instead of mine if you prefer:
    
    $arr = array();
    
    $arr[0]="Code1";
    $arr[1]="Code2";
    $arr[2]="Code3";
    $arr[3]="Code4";
    
    echo $arr[array_rand($arr)];
    PHP:
    That looks a little more like your original code :)
     
    sea otter, Apr 6, 2007 IP