3v4l.org

run code in 300+ PHP versions simultaneously
<?php // id => weight $ads = [ 10 => 5, 20 => 10, 30 => 15 ]; function show_ad($ads) { // calculate the total of all weights $combined = array_sum($ads); // pick a random number from $combined weights $random = rand(0, $combined - 1); // keep subtracting weight until we drop below an ad weight foreach ($ads as $id => $weight) { if ($random < $weight) return $id; $random -= $weight; } return $random; } function simulate_views($ads, $rounds = 100) { $result = []; for ($i = 0; $i < $rounds; $i++) { $id = show_ad($ads); $result[$id] = isset($result[$id]) ? $result[$id]+1: 1; } return $result; } print_r(simulate_views($ads));

preferences:
25.36 ms | 406 KiB | 5 Q