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 class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 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.