Skip to content

Instantly share code, notes, and snippets.

@HazemNoor
Created August 28, 2021 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HazemNoor/d4919462855c2091363dce967f099b2a to your computer and use it in GitHub Desktop.
Save HazemNoor/d4919462855c2091363dce967f099b2a to your computer and use it in GitHub Desktop.
Choose a variation from a weighted experiment
<?php
/**
* Choose a variation from a weighted experiment
* This can be used in A/B testings, in case you need to take a sample of users and apply certain feature on them
*/
function getRandomVariation(array $experiment): string
{
$weightedVariations = [];
foreach ($experiment as $variation => $percentage) {
for ($i = 0; $i < $percentage; $i++) {
$weightedVariations[] = $variation;
}
}
$randomKey = mt_rand(0, count($weightedVariations) - 1);
return $weightedVariations[$randomKey];
}
// Example usage
// To distribute the experiment in a percentage values, make sure that sum of all variations equals to 100
$experiment = [
'original' => 50,
'V1' => 20,
'V2' => 30,
];
// Select one variation from the experiment
$variation = getRandomVariation($experiment);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment