Page 1 of 1

How to avoid doubling up with 'RandomNum'

Posted: Mon Oct 01, 2007 12:40 am
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

Posted: Mon Oct 01, 2007 3:19 am
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.