PHP 8 Intermediate Language Basics · 6 min read

PHP Randomizer for Unbiased Picks

Lesson 38 of 43 in the PHP 8 learning path.

How do I pick a lesson at random without a biased modulo?

Random\Randomizer is the PHP 8.3 API for shuffled copies and integer ranges.

rand() % n is biased for some ranges. pickArrayKeys and getInt are the tools that avoid that.

Syntax & Parameters

Syntax
(new Randomizer())->shuffleArray($titles);

Example

src/Picker.php
<?php
declare(strict_types=1);
use Random\Randomizer;
function pick(array $titles): string
{
    if ($titles === []) {
        throw new InvalidArgumentException('No titles.');
    }
    $random = new Randomizer();
    $shuffled = $random->shuffleArray(array_values($titles));
    return $shuffled[0];
}
echo pick(['Routes', 'Queries', 'Blade']), PHP_EOL;

Expected Output

One of Routes, Queries, or Blade, with each title equally likely.

Line-by-Line Walkthrough

  1. An empty list is rejected.
  2. Randomizer is constructed with the secure engine by default.
  3. array_values makes a 0-based list.
  4. shuffleArray returns a new array.
  5. The first item of that shuffle is the pick.
  6. The original list is not reordered.
  7. Do not use rand modulo for a fair draw.
  8. One echo shows a single title from the three.

Common Pitfalls & Security

Check the edge before you ship it.

  • rand() % count biases some indexes.
  • shuffleArray does not shuffle in place. Use the return value.
  • A Randomizer seeded for tests must not be the production engine.
  • Picking from user-controlled lists is fine. Using the result as a secret token is not.

Best Practices & Modern Standards

Use Randomizer for shuffles and ranges in PHP 8.3.

Reject an empty list before you ask for index 0.

Real-World Use

A classroom warm-up picks one published lesson title at random without favoring the first items.

Frequently Asked Questions

Does shuffleArray change my array?

No. It returns a shuffled copy.

Is this cryptographically strong?

The default engine is suitable for nonces and fair picks. Still do not invent your own token format.

What PHP version?

Randomizer is PHP 8.2 and improved in 8.3.

Why not array_rand?

array_rand is acceptable for a simple key. Randomizer is the API to learn for new code.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…