First of all, your system is just ... stupid . It perpetuates banners with a large number of views, while newly created banners with 0 or more views will never be able to be selected and, therefore, will never actually be visible ...
If you have an array that looks like this:
$banners = array ( 'banner1' => 1, 'banner2' => 2, 'banner3' => 4, 'banner4' => 8, 'banner5' => 16, );
You can use a function like this to weigh one banner:
function Probability($data) { if (is_array($data) === true) { $result = 0; $probability = mt_rand(1, array_sum($data)); foreach ($data as $key => $value) { $result += $value; if ($result >= $probability) { return $key; } } } return false; }
Usage (test it @ CodePad.org or @IDEOne ):
echo Probability($banners);
Example of 100 executions:
Array ( [banner5] => 41 [banner4] => 38 [banner3] => 10 [banner2] => 8 [banner1] => 3 )
source share