How to avoid doubling up with 'RandomNum'

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
malloy
Forum Newbie
Posts: 15
Joined: Fri Jun 01, 2007 2:02 am
Location: Melbourne, Australia

How to avoid doubling up with 'RandomNum'

Post by malloy »

I have the following code to display random pictures.

Code: Select all

<?php 
$ban1 = "apple.jpg";
$url1 = "http://www.apple.com"; 
$ban2 = "orange.jpg";
$url2 = "http://www.orange.com";
$ban3 = "banana";
$url3 = "http://www.banana.com;

$randomNum = rand (1,3);

$image = ${'ban'.$randomNum};

$url= ${'url'.$randomNum};

Print "<a href=".$url." mce_href=".$url." target=\"_blank\" ><img src=".$image." border=0 class=\"thumbs\" width=\"180\" height=\"135\"></a>";
?>
I am then using a simple include statement within my html to call the php.

Code: Select all

td><?php include("image_thumbs.php"); ?></td>
I have been trying to alter my code so that an image cannot be repeated twice. In my full code I have 200 images and each page has 30 include statements. It just some times a picture is repeated twice or even three times.

Does any one have any suggestions how i could get around this?

Cheers,

Malloy
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

Hello. I think you're going about it all wrong. You shouldn't have to include a file 30 times! Plus there's no need for variable variables and hardcoding every image and url into a separate variable.

The following would be a much more elegant solution:

Code: Select all

<?php 
$bans = array(
	array(
		'apple.jpg',
		'http://www.apple.com'
	),
	array(
		'orange.jpg',
		'http://www.oragne.com'
	),
	array(
		'banana.jpg',
		'http://www.banana.com'
	)
);

shuffle($bans);

foreach ($bans AS $ban)
{
	$image = $ban[0];
	$url = $ban[1];
	Print "<a href=\"".$url.\"" mce_href=\"".$url.\"" target=\"_blank\" ><img src=\"".$image.\"" border=0 class=\"thumbs\" width=\"180\" height=\"135\"></a>";
}

?>
Using shuffle() and a foreach(), you will only get one image from the array. You won't have any duplicate images and they will be in a random order.

If you need to use single images on separate parts of the page, storing each image name in an array and then including one that's not in that array would give you a different image every time.
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Post Reply