Hey,

I've taken over a php based website from another developer (ugh!)...

The website uses two include files to display ads down both sides of the page. Now the client wants these ads to display in Random positions....

So, Its easy enough to take the ad text and place it in variables,

$sAdText[0] = '<tr><tr>link text and ad image here</td></tr>';
$sAdText[1] = '<tr><tr>link text and ad image here</td></tr>';
$sAdText[2] = '<tr><tr>link text and ad image here</td></tr>';

How would I go about getting these to display randomly? I can reverse them with a loop I guess, but I'd like a more random solution than that if possible.

Recommended Answers

All 5 Replies

$random_array = array_rand($sAdText, 3);

$random_array = array_rand($sAdText, 3);

Thanks johny_d, thats awesome.

Here is my final code!

<?php
$strAd = array();
$strAd[0] = "html with qoutes escaped...";
$strAd[1] = "html with qoutes escaped...";
.......
$strAd[28] = "html with qoutes escaped...";

srand((float) microtime() * 10000000);
$random_array = array_rand($strAd, 29);

echo "<table cellpadding=\"0\" cellspacing=\"0\">";

for ($i = 1; $i <= 29; $i++) {
    echo $random_array[$i];
}

echo "</table>";
?>

You should use:
for ($i = 0; $i <= 28; $i++) ......
since the keys of your $random_array are from 0 to 28

You should use:
for ($i = 0; $i <= 28; $i++) ......
since the keys of your $random_array are from 0 to 28

True enough:

although instead of :
$random_array = array_rand($strAd, 29);

I'm using:
shuffle($strAd);

As array_rand seam like it can give me duplicates of the same original index whereas shuffle uses all of the original indexes but simply shuffles them.

You really got me on the right track though, Thanks.

You're welcome ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.