Dynadot โ€” .com Registration $8.99

is this the best way ?

Spaceship Spaceship
Watch
Impact
91
hi

i am trying to create a simple adsense rotation script which would display the ads in a certain ratio

if i have to distribute the ads in 50-50% ratio then i would follow this
Code:
<?php 
$rand = rand(1,2);
if ($rand == 1) 
print 'adsense code 1';

elseif ($rand == 2) 
print 'adsense code 2;
?>

but the problem is suppose i want to distribute the ads into a certain ratio of say 70-30%
then should i do it manually by using
Code:
rand(1,2,3,4,5,6,7,8,9,0)
and then using if statement to print out "code 1" 7 times and "code 2" 3 times?

or is there any better and more efficient way to do this all?
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
Unstoppable DomainsUnstoppable Domains
champ_rock said:
Code:
<?php 
$rand = rand(1,2);
if ($rand == 1) 
print 'adsense code 1';

elseif ($rand == 2) 
print 'adsense code 2;
?>

a more eficient way would be

Code:
$adsense['1']= "code here";
$adsense['2']= "code here";
$rand = rand(1,2);


echo $adsense[$rand];

if you use rand(1,9) it gives you a random number between 1 and 9.
if you want percentages and want them precise you should use a database.
 
0
•••
Here's a function that returns 0 or 1 based on which side of a user-definable threshold the random number ends up on. Explanation after the code:

PHP:
function rand_threshold($threshold)
{
     return mt_rand(1,100) <= $threshold ? 0 : 1;
}

The function returns 0 if the random value is less than or equal to the threshold passed in as a parameter, or 1 if it's greater.

So...if you call the function as such:

PHP:
$rand = rand_threshold(30);

$rand will be 0 30% of the time, and 1 70% of the time. You can use the returned values as indexes into the array of ad codes.

If you want the opposite to happen, e.g. the SECOND ad code to come up only 30% of the time, just invert the threshold:

PHP:
$rand = rand_threshold(70);

For the 50/50 scenario you first outlined, it should be obvious what to do :)

PHP:
$rand = rand_threshold(50);
 
1
•••
Dynadot โ€” .com Registration $8.99Dynadot โ€” .com Registration $8.99
Unstoppable Domains
Domain Recover
DomainEasy โ€” Live Options
  • The sidebar remains visible by scrolling at a speed relative to the pageโ€™s height.
Back