Display a Random Link or Text with PHP

by CarcaBot on July 24, 2009 · 0 comments

This PHP code snippet will provide you with the necessary code to output a random item selected from a predefined array in PHP. This is useful for displaying random quotes, links, or images.

This example uses an array of cookies, and prints out a random item from the list as an image, and links to the information page.

<?php
        $cookieList['flower']            = 'flowers';
        $cookieList['eiffel_tower']               = 'tower';
        $cookieList['flower_yellow']        = 'flowers';
        $cookieList['heart_dress']                  = 'dress_tux';       
        $cookieList['heart_flower']               = 'hearts';
        $cookieList['heart_suit']                     = 'dress_tux';
        $cookieList['maple_leaf_red']      = 'leaves';
        $cookieList['maple_leaf_white']  = 'leaves';     
        $cookieList['sunflower']                        = 'flowers';
        $cookieList['wedding_cake_orange']      = 'cakes';
        $cookieList['wedding_cake_purple']      = 'cakes';
        $cookieList['wedding_cake_white']       = 'cakes';
       
        srand ( ( double ) microtime() * 1000000 );
        $random_number = rand ( 0, count( $cookieList )1 );

        $i = 0;
        $cookieToDisplay = 'flower';
       
        foreach ( $cookieList as $key => $item )
        {
                $i += 1;
                if ( $i == $random_number )
                {
                        $cookieToDisplay = $key;
                        break;
                }
        }
?><a href="cookies_<?php echo $cookieList[$cookieToDisplay]?>.php"><img
 style="border: 0px solid ; width: 58px;"
 alt="<?php echo $cookieToDisplay ?>" src="images/cookies/<?php echo $cookieToDisplay ?>_tn.png" />
<br />info</a>

Previous post:

Next post: