php
45 lines · 8 steps
Weighted random selection in PHP
Pick a variant at random with each option's odds proportional to its assigned weight.
Explained by
highlit
1<?php
2
3namespace App\Experiments;
4
5use InvalidArgumentException;
6
7final class WeightedVariantPicker
8{
9 private array $variants;
10 private int $total;
11
12 public function __construct(array $weights)
13 {
14 if ($weights === []) {
15 throw new InvalidArgumentException('At least one variant is required.');
16 }
17
18 $this->variants = [];
19 $cumulative = 0;
20
21 foreach ($weights as $name => $weight) {
22 if ($weight <= 0) {
23 throw new InvalidArgumentException("Weight for \"{$name}\" must be positive.");
24 }
25
26 $cumulative += $weight;
27 $this->variants[] = ['name' => $name, 'threshold' => $cumulative];
28 }
29
30 $this->total = $cumulative;
31 }
32
33 public function pick(): string
34 {
35 $roll = random_int(1, $this->total);
36
37 foreach ($this->variants as $variant) {
38 if ($roll <= $variant['threshold']) {
39 return $variant['name'];
40 }
41 }
42
43 return $this->variants[array_key_last($this->variants)]['name'];
44 }
45}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Turning weights into cumulative thresholds lets a single random roll map cleanly to a weighted choice.
- 2Validating inputs in the constructor keeps the sampling method simple and always correct.
- 3A final fallback return guards against floating-point or off-by-one gaps in threshold coverage.
Related explainers
php
<?php namespace App\View\Components;
Building a breadcrumb component in Laravel
blade components
url parsing
string manipulation
Intermediate
8 steps
java
@Component @Order(Ordered.HIGHEST_PRECEDENCE) public class TenantResolutionFilter extends OncePerRequestFilter {
How a tenant-resolution filter works in Spring
multi-tenancy
servlet-filter
thread-local
Intermediate
8 steps
go
package events import ( "net/http"
Two-pass JSON dispatch in Gin
polymorphic-json
request-binding
validation
Intermediate
8 steps
php
final class FieldEncryptor { private string $key;
Authenticated field encryption with libsodium
encryption
libsodium
authenticated-encryption
Intermediate
7 steps
typescript
import { Injectable, PipeTransform, ArgumentMetadata,
A custom validation pipe in NestJS
validation
dto
recursion
Intermediate
10 steps
ruby
module CreditCard module_function def valid?(number)
Validating credit card numbers with Luhn
checksum
luhn-algorithm
validation
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/weighted-random-selection-in-php-explained-php-4744/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.