haphpiness

These are things in PHP which make me genuinely_happy();

clamp() — The Three-Line Helper Everyone Rewrites

Not out yet. PHP 8.6 is due 19 November 2026, and this one is written and voted through.

Every codebase has this function. It is usually called clamp, it lives in a Helpers class nobody is proud of, and it is written slightly differently in each project.

// The one you have written, more than once.
function clamp($value, $min, $max) {
    return max($min, min($max, $value));
}

// The nesting is easy to get backwards, and when you do,
// it fails silently by returning a plausible wrong number.
clamp(2, min: 1, max: 3);      // 2, already in range
clamp(0, min: 1, max: 3);      // 1
clamp(6, min: 1, max: 3);      // 3

clamp("a", "c", "g");          // "c", standard comparison rules
clamp(M_PI, -INF, INF);        // 3.141592653589793

// And it refuses nonsense instead of guessing:
clamp(4, 8, 6);                // ValueError: $min must be smaller than or equal to $max

The max($min, min($max, $value)) trick returns a number no matter how you nest it, so a transposed bound produces bad output rather than an error. clamp() throws a ValueError when $min exceeds $max, and on NAN bounds. A NAN value passes through unchanged, because there is no sensible bound to snap it to.

It is a small function. That is the argument for it: small functions everyone writes are exactly the ones that should be in the standard library, written once, with the edge cases decided by people who argued about them in public.

Significance: Batteries Included

A standard library earns its keep on the boring functions. str_contains() was mocked as trivial and is now in every codebase, because the trivial thing was previously done wrong: strpos() !== false caught people out for twenty years. clamp() is the same trade. Not exciting, throws on the mistake you were going to make, and quietly deletes a helper file from thousands of projects.