Simple Probability Distribution with PHP

We’ve all been there, trying to juggle two or more things for either split testing or just because you want some variety. This came up recently for me with juggling advertising networks and I wrote some simply code to handle it. The premise is simple, you assign weights to the items that you want to distribute, tally up the weights, generate a random number and grab your results. With the following code, I recommend that the weights total 100, but they don’t have to (you’ll have to do the math to determine the percentage if you don’t keep it to 100)

$items = array(
    'ten'         => 10,
    'fifty'       => 50,
	  'twenty five' => 25,
	  'fifteen'     => 15,

$max = 0;

foreach ($items as $item => $weight) {
	$max		      += $weight;
	$items[$item]  = $max;

$random = mt_rand(1, $max);

foreach ($items as $item => $max) {
	if ($random <= $max) {

echo 'The selected item is "' . $item . '"';

It’s not an exact science, but it gets the job done within reason. I am using this code in production but I have some ideas on how to avoid looping over all of the items (which could get out of hand if you had thousands and thousands of items).

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.