05: Limit Values with clamp()
Overview
Section titled “Overview”Keep a page-size setting within an inclusive range. Use the same operation to cap a retry delay represented by a duration.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable clamp.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/05-clamp/clamp.php<?php
declare(strict_types=1);
use Time\Duration;
foreach ([-5, 25, 150] as $requested) { printf("%d -> %d\n", $requested, clamp($requested, 1, 100));}
$timeout = clamp( Duration::fromMilliseconds(300), Duration::fromSeconds(1), Duration::fromSeconds(5),);echo 'Timeout seconds: ', $timeout->seconds, PHP_EOL;
try { clamp(3, 10, 1);} catch (ValueError) { echo "Rejected reversed limits\n";}Expected Result
Section titled “Expected Result”-5 -> 125 -> 25150 -> 100Timeout seconds: 1Rejected reversed limitsWhy It Works
Section titled “Why It Works”PHP uses its ordinary comparison rules and returns the original value when it is within bounds. Outside the range you get the appropriate boundary value, including its original type. Reversed limits throw a ValueError.
Exercise
Section titled “Exercise”Clamp requests of 0, 25, and 1,000 to the range 1–100. Verify that you obtain 1, 25, and 100.
Wrap-up
Section titled “Wrap-up”Continue with Type-Safe Sorting with SortDirection.