Skip to content

05: Limit Values with clamp()

Keep a page-size setting within an inclusive range. Use the same operation to cap a retry delay represented by a duration.

  • 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.

A runnable clamp.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/05-clamp/clamp.php
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";
}
-5 -> 1
25 -> 25
150 -> 100
Timeout seconds: 1
Rejected reversed limits

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.

Clamp requests of 0, 25, and 1,000 to the range 1–100. Verify that you obtain 1, 25, and 100.

Continue with Type-Safe Sorting with SortDirection.