Problem with PHP array_rand command

Discussion in 'PHP' started by jis2507, Feb 7, 2010.

  1. #1
    Hey people,

    Could somebody please help me out here?

    I am trying to make a simple text rotator on my site.

    The code I am using is this:
    
    <?php
    $text=array("text1", "text2", "text3", "text4", "text5");
    $random=array_rand($text, 1);
    echo $text[$random[0]] . "\n";
    ?>
    
    PHP:
    This however is not working for me.

    It DOES work if I change it to display TWO text parts. I only want it to display one though.

    Any help would be greatly appreciated.
     
    Last edited: Feb 7, 2010
    jis2507, Feb 7, 2010 IP
  2. mrhrk01

    mrhrk01 Well-Known Member

    Messages:
    664
    Likes Received:
    28
    Best Answers:
    0
    Trophy Points:
    145
    #2
    I think the following code should work:

    
    <?php
    $text=array("text1", "text2", "text3", "text4", "text5");
    $random=array_rand($text, 1);
    echo $text[$random] . "\n";
    ?>
    
    PHP:
     
    mrhrk01, Feb 7, 2010 IP
  3. jis2507

    jis2507 Greenhorn

    Messages:
    39
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    18
    #3
    Works perfectly!

    Thanks heaps!
     
    jis2507, Feb 7, 2010 IP
  4. historiasdemaria

    historiasdemaria Member

    Messages:
    138
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    28
    #4
    I just had a problem with this function.. when the array is too big it doesn't work so well and you get no randoms at all, I suggest you this code:

    $n=100; // Or your max desired value
    for($i=1;$i<=($n+1);$i++)
    {
    	$input[]=rand(1,$n);
    }
    PHP:
    :)
     
    historiasdemaria, Mar 4, 2011 IP