Simple Probability Distribution with PHP

Josh Sherman
1 min read
Software Development 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 crazy if you had thousands and thousands of items).

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles