0

trying to set up a simple embed box to echo url and randomize source anchor text. I achieved both with this:

<textarea class="cf" onclick="this.focus();this.select()" readonly="readonly">
<iframe src="<?php
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $url;
?>" width="550px" height="400px" frameborder="0" scrolling="auto" allowtransparency="true"><a href="http://example.com/"><?php 
$raAnchor = array(1 => 'example.com', 
           2 => 'http://example.com/', 
           3 => 'www.example.com', 
           4 => 'Click here');  
$raNumber = count($raAnchor); 
echo $raAnchor[rand(1, $raNumber)]; 
?></a></iframe>
</textarea>

The problem: how do I weight random results from the array to favor a particular echo? For example, would like example.com to echo out 50% of the time. I guess I could just put more example.com in the array like this:

1 => 'example.com', 
2 => 'example.com', 
3 => 'example.com', 
4 => 'example.com', 
5 => 'http://example.com/', 
6 => 'www.example.com', 
7 => 'Click here');  

Seems there has to be a more elegant solution. I'm new to programming, and php I understand the least so if you could point me in the right direction I can take it from there.

Thanks.

Jay
  • 87
  • 3
  • 11
  • possible duplicate of [Generating random results by weight in PHP?](http://stackoverflow.com/questions/445235/generating-random-results-by-weight-in-php) – nickb Jun 01 '12 at 13:38

3 Answers3

1

You can do this:

<?php
    if(rand(1,2) == 1)
    {
        //Example goes here
    }
    else
    {
        //Everything else
    }
?>

You can do the same with intervals. For example:

<?php
    $r = rand(1,10); 
    if($r >=1 && $r < 4)
    {
        /* 30% */
    }
    else if($r >=4 && $r < 9)
    {
        /* 60% */
    }
    else
    {
        /* 10% */
    }
?>
1

You can always generate a random number 1-100, then if <= 40, go with 1. Otherwise, do another random to select 2-7.

blackcatweb
  • 1,003
  • 1
  • 10
  • 11
1

just pick a big MAX value and play it in 1/100 basis (more flexible;more random)

if (($index = mt_rand(1,1000))<500) {
   // yes, 50%
   shuffle($arr);
   return $arr[$index];
}
else {
   // the other 50%
}

or just random:

shuffle($arr);
return $arr[ array_rand($arr) ];