When developing applications, developers frequently need to keep values within a specific range. For example, an e-commerce application may need to limit product discounts, a web application may need to restrict pagination values, and a user interface may need to keep volume or brightness settings within acceptable limits.
Before PHP 8.6, developers commonly used combinations of min() and max() or conditional statements to perform these operations. Although these approaches worked, they often required additional code and made simple validation logic harder to read.
PHP 8.6 introduces the built-in clamp() function, which provides a straightforward way to keep a value within a specified minimum and maximum range.
The function checks whether a value falls within the given boundaries. If the value is below the minimum, it returns the minimum. If it is above the maximum, it returns the maximum. Otherwise, it returns the original value.
An important feature of clamp() is that it is not limited to numeric values. It can also work with other comparable values, including strings, DateTimeImmutable objects, and the Duration class introduced in PHP 8.6.
In this article, we will explore the clamp() function, understand its syntax, and implement practical examples for everyday PHP development.
What Is the clamp() Function in PHP 8.6?
The clamp() function is a built-in PHP function introduced in PHP 8.6. It restricts a given value to a specified range.
Its syntax is:
clamp(
mixed $value,
mixed $min,
mixed $max
): mixed
The function accepts three arguments:
Parameter | Description |
|---|
value | The original value that needs to be restricted |
min | The minimum allowed boundary |
max | The maximum allowed boundary |
The function returns the original value if it is already within the range. Otherwise, it returns the nearest boundary.
Consider the following example:
<?php
echo clamp(-10, 0, 100) . PHP_EOL;
echo clamp(50, 0, 100) . PHP_EOL;
echo clamp(110, 0, 100) . PHP_EOL;
Output:
0
50
100
Here is what happens:
When the value is -10, clamp() returns 0 because the value is below the minimum.
When the value is 50, it returns 50 because the value is already within the range.
When the value is 110, it returns 100 because the value exceeds the maximum.
This makes clamp() useful whenever an application needs to enforce minimum and maximum boundaries.
Why PHP Introduced the clamp() Function
Before PHP 8.6, developers generally used combinations of min() and max() to restrict values.
For example:
<?php
$value = 150;
$minimum = 0;
$maximum = 100;
$result = max(
$minimum,
min($value, $maximum)
);
echo $result;
Output:
100
This approach works, but developers must understand the order of the min() and max() operations.
Another option is to use conditional statements:
<?php
function limitValue(
int $value,
int $minimum,
int $maximum
): int {
if ($value < $minimum) {
return $minimum;
}
if ($value > $maximum) {
return $maximum;
}
return $value;
}
echo limitValue(150, 0, 100);
This implementation is easy to understand, but creating similar functions throughout an application introduces unnecessary duplication.
PHP 8.6 simplifies this operation with a native function:
<?php
echo clamp(150, 0, 100);
The code is shorter and communicates the intention directly.
The new function also provides built-in validation for invalid boundaries and handles comparable values beyond ordinary numbers.
Understanding How clamp() Works
The clamp() function follows three basic comparison steps.
It checks whether the supplied value is greater than the maximum boundary. If so, it returns the maximum.
It checks whether the supplied value is smaller than the minimum boundary. If so, it returns the minimum.
If neither condition is true, it returns the original value.
Consider the following example:
<?php
$value = 75;
$minimum = 10;
$maximum = 90;
$result = clamp(
$value,
$minimum,
$maximum
);
var_dump($result);
Output:
int(75)
The value is already within the specified range, so PHP returns the original value.
One important detail is that clamp() returns the original value or one of the original boundary values. It does not automatically convert the result into another numeric type.
For example:
<?php
$result = clamp(5, 10.0, 20.0);
var_dump($result);
Output:
float(10)
The result comes from the minimum boundary, which is a float.
This behavior is useful when working with different numeric types, but developers should understand how PHP handles comparisons between those types.
Using clamp() With Integer Values
One of the most common use cases is restricting integer values.
For example, an application may allow users to select a quantity between 1 and 50.
<?php
$requestedQuantity = 75;
$minimumQuantity = 1;
$maximumQuantity = 50;
$quantity = clamp(
$requestedQuantity,
$minimumQuantity,
$maximumQuantity
);
echo "Selected quantity: " . $quantity;
Output:
Selected quantity: 50
If the user requests a quantity of 75, the application restricts it to 50.
This is useful for:
However, clamping should not replace input validation. If an application must reject invalid user input rather than silently adjust it, developers should validate the original value before applying clamp().
Using clamp() With Floating-Point Values
Many applications work with decimal values instead of integers.
For example, an application may allow users to configure a percentage between 0 and 100.
<?php
$discount = 125.75;
$minimumDiscount = 0.0;
$maximumDiscount = 100.0;
$finalDiscount = clamp(
$discount,
$minimumDiscount,
$maximumDiscount
);
echo "Discount: " . $finalDiscount . "%";
Output:
Discount: 100%
The requested discount exceeds the maximum allowed value, so clamp() returns 100.
Developers can also use the function with decimal ranges:
<?php
$temperature = 42.75;
$minimumTemperature = 18.5;
$maximumTemperature = 35.0;
$temperature = clamp(
$temperature,
$minimumTemperature,
$maximumTemperature
);
echo $temperature;
Output:
35
This can be useful for application settings, measurement systems, and numerical configuration.
For financial calculations, remember that floating-point arithmetic has precision limitations. Use appropriate decimal or integer-based money representations when exact monetary calculations are required.
Practical Example: Limiting Product Discounts in an E-Commerce Application
Let's consider a practical e-commerce scenario.
An application allows administrators to configure discounts for different products. The business rules specify that discounts must remain between 0% and 70%.
Instead of manually checking every discount value, developers can use clamp().
<?php
function calculateDiscount(
float $productPrice,
float $requestedDiscount
): float {
$discount = clamp(
$requestedDiscount,
0.0,
70.0
);
return $productPrice * ($discount / 100);
}
$products = [
[
"name" => "Laptop",
"price" => 80000,
"discount" => 80
],
[
"name" => "Keyboard",
"price" => 3000,
"discount" => 20
],
[
"name" => "Monitor",
"price" => 15000,
"discount" => -10
]
];
foreach ($products as $product) {
$discountAmount = calculateDiscount(
$product["price"],
$product["discount"]
);
$finalPrice = $product["price"] - $discountAmount;
echo $product["name"] . PHP_EOL;
echo "Original Price: " .
$product["price"] . PHP_EOL;
echo "Discount Amount: " .
$discountAmount . PHP_EOL;
echo "Final Price: " .
$finalPrice . PHP_EOL;
echo PHP_EOL;
}
The application automatically restricts discounts to the configured range.
For example:
An 80% discount becomes 70%.
A 20% discount remains unchanged.
A negative discount becomes 0%.
This reduces repeated boundary-checking logic.
In a production e-commerce application, the original requested discount should also be validated against business permissions. An administrator who attempts to configure an invalid discount may need an error rather than silent adjustment. Monetary calculations should also use an appropriate decimal or minor-unit representation.
Using clamp() for Pagination Limits
Pagination is another common area where developers need to restrict numeric values.
Suppose an API accepts a page number and a page size from query parameters.
A client might send an extremely large page size, which can result in unnecessary database work and increased memory usage.
The clamp() function can restrict the page size.
<?php
$page = (int) ($_GET["page"] ?? 1);
$pageSize = (int) ($_GET["pageSize"] ?? 20);
$page = max(1, $page);
$pageSize = clamp(
$pageSize,
1,
100
);
$offset = ($page - 1) * $pageSize;
echo "Page: " . $page . PHP_EOL;
echo "Page Size: " . $pageSize . PHP_EOL;
echo "Offset: " . $offset;
Here, the page size is restricted to a maximum of 100 records.
The application also ensures that the page number does not fall below 1.
This helps protect database queries from unnecessarily large page-size requests.
However, this example assumes that the input can be safely converted to an integer. In production applications, developers should validate malformed input instead of automatically converting every supplied value.
For example, a request containing a non-numeric page size should normally be rejected or handled using an explicit default policy.
Using clamp() With Strings
The clamp() function is not restricted to numbers.
PHP supports comparisons between strings, which means clamp() can also restrict string values according to PHP's standard comparison rules.
For example:
<?php
$grade = "J";
$minimumGrade = "A";
$maximumGrade = "F";
$result = clamp(
$grade,
$minimumGrade,
$maximumGrade
);
var_dump($result);
Output:
string(1) "F"
In this example, PHP compares the strings using their normal string comparison behavior.
The value J is greater than F, so clamp() returns F.
This can be useful in situations involving ordered string identifiers or labels.
However, developers should not assume that arbitrary strings have a meaningful business order.
For example, product categories, user roles, and status names should generally be validated against an explicit allowed set rather than restricted using alphabetical comparison.
Using clamp() With DateTimeImmutable
Another useful feature is the ability to work with objects that support comparison.
DateTimeImmutable objects can be compared using standard comparison operators.
This makes them suitable for clamp().
Consider an application that allows users to schedule appointments only within a specified booking period.
<?php
$requestedDate = new DateTimeImmutable(
"2026-08-01"
);
$minimumDate = new DateTimeImmutable(
"2026-08-15"
);
$maximumDate = new DateTimeImmutable(
"2026-09-15"
);
$bookingDate = clamp(
$requestedDate,
$minimumDate,
$maximumDate
);
echo $bookingDate->format("Y-m-d");
Output:
2026-08-15
The requested date is earlier than the minimum booking date, so the function returns the minimum date.
This approach can be useful when restricting date values within a valid period.
However, date comparison requires careful handling of timezones and business rules. A production booking system may need to reject dates outside the allowed period rather than silently move them to the nearest boundary.
Using clamp() With the Duration Class
PHP 8.6 also introduces the Time\Duration class for representing fixed amounts of elapsed time.
Because Duration objects support comparison, they can be used with clamp().
This is particularly useful for timeout configuration and retry delays.
<?php
use Time\Duration;
$requestedTimeout = Duration::fromSeconds(30);
$minimumTimeout = Duration::fromMinutes(1);
$maximumTimeout = Duration::fromMinutes(10);
$timeout = clamp(
$requestedTimeout,
$minimumTimeout,
$maximumTimeout
);
echo $timeout->seconds;
Output:
60
The requested timeout is 30 seconds, but the application requires a minimum of one minute.
The function therefore returns the minimum Duration value.
This example demonstrates how clamp() works with objects that support meaningful comparisons.
It is useful when building applications that need consistent timeout and retry configurations.
Handling Invalid Boundaries and NAN Values
The clamp() function validates its boundaries before returning a result.
There are two important situations developers should handle.
When the Minimum Is Greater Than the Maximum
The minimum boundary must be smaller than or equal to the maximum boundary.
Consider the following example:
<?php
try {
$result = clamp(
50,
100,
10
);
echo $result;
} catch (ValueError $exception) {
echo "Invalid range: " . $exception->getMessage();
}
In this example, the minimum is 100 and the maximum is 10.
PHP throws a ValueError because the range is invalid.
Developers should validate configurable boundaries before calling clamp().
When a Boundary Contains NAN
PHP also rejects NAN as either boundary.
<?php
try {
$result = clamp(
50.0,
NAN,
100.0
);
echo $result;
} catch (ValueError $exception) {
echo "Invalid boundary value.";
}
A NAN value cannot provide a meaningful minimum or maximum comparison.
The function throws a ValueError when either boundary is NAN.
When the Input Value Is NAN
There is an important difference between NAN as an input and NAN as a boundary.
If the supplied value is NAN, clamp() returns NAN.
<?php
$result = clamp(
NAN,
0.0,
100.0
);
var_dump(is_nan($result));
Output:
bool(true)
Therefore, applications that accept floating-point input should validate NAN values explicitly when they are not allowed.
Understanding clamp() Type Comparisons
One of the most important details of clamp() is that its parameters use mixed types.
This means PHP applies its standard comparison rules when comparing values of different types.
Consider the following example:
<?php
$result = clamp(
"25",
10,
100
);
var_dump($result);
PHP can compare the numeric string with the integer boundaries.
However, non-numeric strings and integers may produce results that are not obvious from the function call.
For example, PHP uses its standard comparison rules when comparing a non-numeric string with an integer.
This can lead to surprising results if an application mixes unrelated types.
The strict_types declaration does not change these comparison rules because clamp() accepts mixed parameters.
A good practice is to use compatible types for all three arguments.
For example:
<?php
$value = 25;
$minimum = 10;
$maximum = 100;
$result = clamp(
$value,
$minimum,
$maximum
);
Using the same type makes the code easier to understand and reduces unexpected comparison behavior.
clamp() vs. min() and max()
PHP developers already use min() and max() for comparing values.
The new clamp() function provides a more direct solution when the goal is to restrict a value to a specific range.
Feature | clamp() | min() and max() |
|---|
Main purpose | Restrict a value within boundaries | Find the smallest or largest value |
Range restriction | Built in | Requires combining functions |
Syntax | Single function call | Nested function calls |
Invalid range validation | Throws ValueError | No equivalent range validation |
NAN boundaries | Rejected | Different behavior |
Comparable objects | Supported when comparisons are supported | Supported when comparisons are supported |
PHP availability | PHP 8.6 and later | Available in earlier PHP versions |
Before PHP 8.6:
<?php
$value = 150;
$result = max(
0,
min($value, 100)
);
echo $result;
PHP 8.6:
<?php
$value = 150;
$result = clamp(
$value,
0,
100
);
echo $result;
Both approaches restrict the value to the specified range.
The native function makes the intention clearer and provides validation for invalid boundaries.
Advantages of the clamp() Function
The new clamp() function provides several benefits for PHP applications.
Less Code
Developers can replace nested min() and max() calls or repeated conditional statements with a single function call.
This reduces unnecessary code.
Better Readability
The function name clearly communicates its purpose.
Developers can understand that a value is being restricted to a range without examining multiple conditions.
Built-In Boundary Validation
The function throws a ValueError when the minimum is greater than the maximum or when either boundary is NAN.
This helps prevent invalid range configurations.
Supports Multiple Comparable Types
The function works with integers, floats, strings, and comparable objects.
This makes it useful beyond ordinary numerical calculations.
Preserves the Original Value Type
The function returns the original value when it falls within the range.
When a boundary is returned, the boundary's original type is preserved.
Useful Across Application Layers
The function can be used in API development, configuration management, data processing, e-commerce applications, and scheduling systems.
Disadvantages and Limitations
Although clamp() simplifies range restrictions, it is not suitable for every validation requirement.
Requires PHP 8.6 or Later
The native function is not available in PHP 8.5 and earlier versions.
Applications running older PHP versions need a custom implementation or a compatible library.
Uses PHP's Standard Comparison Rules
The mixed parameter types can produce unexpected results.
Developers should avoid comparing unrelated types without explicitly validating their inputs.
Does Not Replace Input Validation
The function restricts a value but does not determine whether the original input is valid.
For example, silently changing an invalid discount or booking date may not be appropriate for every business operation.
Does Not Handle Business Rules Automatically
The function does not understand application-specific requirements.
Developers must still implement permissions, authorization, currency rules, and other domain validations.
NAN Input Requires Attention
A NAN input value remains NAN.
Applications that require finite numeric values must validate the input separately.
Best Practices for Using clamp() in Production
The following practices can help developers use clamp() correctly.
Use compatible data types. Keep the value, minimum, and maximum boundaries consistent whenever possible. Avoid unnecessary comparisons between strings, integers, booleans, and objects.
Validate user input before applying clamp(). The function should not replace validation of malformed values or unexpected input types.
Validate configurable boundaries. Make sure the minimum is not greater than the maximum before processing application data.
Handle NAN values explicitly. If the application accepts floating-point values, check for NAN and infinity where appropriate.
Use meaningful boundary variables. Instead of passing unexplained numbers directly, create variables such as $minimumPageSize and $maximumPageSize.
Avoid silently correcting invalid business data. In some situations, rejecting an invalid value is better than automatically replacing it with a boundary.
Use clamp() for genuine range restrictions. Do not use it when the application needs to validate membership in a fixed list of allowed values.
Consider numeric precision. For financial calculations, use appropriate decimal representations instead of relying entirely on floating-point values.
Add unit tests for boundary conditions. Test values below the minimum, equal to the minimum, inside the range, equal to the maximum, and above the maximum.
Verify PHP version compatibility. Make sure development, testing, and production environments support PHP 8.6.
Common Mistakes Developers Should Avoid
Passing the Minimum Greater Than the Maximum
One common mistake is providing an invalid range.
<?php
$result = clamp(50, 100, 0);
This throws a ValueError.
Always ensure that the minimum is less than or equal to the maximum.
Assuming clamp() Validates User Input
Consider the following example:
<?php
$pageSize = clamp(
(int) ($_GET["pageSize"] ?? 20),
1,
100
);
Casting arbitrary input to an integer before calling clamp() can hide invalid input.
For example, a non-numeric string may become zero.
A better approach is to validate the original value and then apply the range restriction.
Mixing Incompatible Data Types
Avoid passing a non-numeric string with integer boundaries unless the comparison behavior is intentional.
The function follows PHP's normal comparison rules, which may not match the application's business requirements.
Expecting NAN to Be Automatically Corrected
A NAN input remains NAN.
Validate floating-point values explicitly when the application requires a finite result.
Using clamp() Instead of an Allowed-Values Check
Suppose an application supports only three user roles:
Administrator
Editor
Viewer
These values do not represent a meaningful continuous range.
Use an allowed-values validation instead of clamp().
Troubleshooting clamp() Issues
Problem | Possible Cause | Recommended Solution |
|---|
Call to undefined function clamp() | PHP version is older than 8.6 | Upgrade PHP or use a custom implementation |
ValueError is thrown | Minimum is greater than maximum | Correct the boundary configuration |
ValueError involving NAN | Minimum or maximum contains NAN | Validate boundary values before calling clamp() |
Unexpected result with strings | PHP comparison rules are being applied | Use compatible types and explicit validation |
Result remains NAN | Input value is NAN | Check the input using is_nan() |
Incorrect pagination result | Input was converted without validation | Validate the original request parameter |
Unexpected decimal result | Floating-point precision limitations | Use appropriate decimal arithmetic for financial values |
Conclusion
The clamp() function in PHP 8.6 provides a simple and consistent way to restrict values within a specified range. It replaces common combinations of min() and max() with a more readable native function.
Developers can use it for product discounts, pagination limits, application settings, timeout configurations, date restrictions, and other range-based operations.
One of its useful capabilities is support for comparable values beyond integers and floats, including strings, DateTimeImmutable objects, and PHP 8.6 Duration objects.
However, developers should understand its mixed-type comparison behavior, validate input data, and handle invalid boundaries and NAN values correctly.
For modern PHP applications, clamp() is a useful addition that reduces repetitive range-checking code and makes application logic easier to read and maintain.
PHP 8.6clamp functionvalue rangesinput validationmin maxPHP functions
Join the conversation! Your thoughts help the community grow.