Jump to content

Selecting a number from a list at random?


misterm

Recommended Posts

Hi

 

I have been pulling my hair out over this.

 

I am trying to randomly display an include file within a php web page.

 

Each include has a number as it's name i.e. 15.php 17.php etc.

 

becuase these files aren't numbered 1 to 100 for example, I only need to show a select few at random, so my list may be 7.php 9.php 12.php 22.php etc.

 

I tried adapting the script at:

 

http://www.pixel2life.com/publish/tutorials/904/php_random_content_or_advertisment/

 

and then <? include ($myRandomNumber.'.php'); ?>

 

but I can't seem to get it to work and this seems a really clumbsy way of doing this.

 

I tried selecting a number from an array, but couldn't get that to work either  :/

 

If anyone has a better suggestion, it would be greatly appreciated.

 

Many thanks

 

Mr M  :)

 

You can do well and spit out weighted results, for example if you wish "your" add was displayed slightly more, etc.

 

function randweighted($numbers) {
    $total = 0;
    foreach ($numbers as $number => $weight) {
        $total += $weight;
        $distribution[$number] = $total;
    }
    $rand = mt_rand(0, $total - 1);
    foreach ($distribution as $number => $weights) {
        if ($rand < $weights) { return $number; }
    }
}

$ads = array(51 => 2000, 
                    41  => 5000,
                    23  => 3000);

include (randweighted($ads) . '.php');

You can do well and spit out weighted results, for example if you wish "your" add was displayed slightly more, etc.

 

function randweighted($numbers) {
    $total = 0;
    foreach ($numbers as $number => $weight) {
        $total += $weight;
        $distribution[$number] = $total;
    }
    $rand = mt_rand(0, $total - 1);
    foreach ($distribution as $number => $weights) {
        if ($rand < $weights) { return $number; }
    }
}

$ads = array(51 => 2000, 
                    41  => 5000,
                    23  => 3000);

include (randweighted($ads) . '.php');

 

Did you forget something? :D

Thanks for the replies.

 

Think I just figured it out. I just need an array of several pre-defined numbers. Then I want to extract just one of those numbers randomly.

 

<?

$randomProductID= array("50","63","82","92","99");

$randomProduct=array_rand($randomProductID,2);

echo "Randon number ".$randomProductID[$randomProduct[0]];

?>

 

This seems to work.

 

Thnaks again for the replies

 

MrM

 

 

 

 

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.