Created
August 28, 2021 11:23
-
-
Save HazemNoor/d4919462855c2091363dce967f099b2a to your computer and use it in GitHub Desktop.
Choose a variation from a weighted experiment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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