PHP Code

Display a Random Link or Text with PHP

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&#91;'flower'&#93;				= 'flowers';
	$cookieList&#91;'eiffel_tower'&#93;			= 'tower';
	$cookieList&#91;'flower_yellow'&#93;		= 'flowers';
	$cookieList&#91;'heart_dress'&#93;			= 'dress_tux';	
	$cookieList&#91;'heart_flower'&#93;			= 'hearts';
	$cookieList&#91;'heart_suit'&#93;			= 'dress_tux';
	$cookieList&#91;'maple_leaf_red'&#93;		= 'leaves';
	$cookieList&#91;'maple_leaf_white'&#93;		= 'leaves';	
	$cookieList&#91;'sunflower'&#93;			= 'flowers';
	$cookieList&#91;'wedding_cake_orange'&#93;	= 'cakes';
	$cookieList&#91;'wedding_cake_purple'&#93;	= 'cakes';
	$cookieList&#91;'wedding_cake_white'&#93;	= '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&#91;$cookieToDisplay&#93;?>.php"><img
 style="border: 0px solid ; width: 58px;"
 alt="<?php echo $cookieToDisplay ?>" src="images/cookies/<?php echo $cookieToDisplay ?>_tn.png" />
<br />info</a>
Share

1 Comments

  1. create!!

    It works fine. I linked it to my todo list by categories

    thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image