大网数据广告活动
PHP 语言与运行手册

clamp · Return the given value if in range, else return the nearest bound

· 52CE 我爱测

clamp — Return the given value if in range, else return the nearest bound

clamp

(PHP 8 >= 8.6.0)

clamp — Return the given value if in range, else return the nearest bound

说明

function clamp(mixed $value, mixed $min, mixed $max): mixed

Return the given value if in range of min and max. Else if it's lower than min, return min. Else return max.

注意:

Values of different types will be compared using the standard comparison rules. For instance, when a non-numeric string is compared to an int, the int is cast to string and the values are compared as strings. Multiple non-numeric string values are also compared as strings. The actual value returned will be of the original type with no conversion applied.

警告

Be careful when passing arguments of different types because clamp() can produce unpredictable results.

参数

value

Any comparable value to be clamped between min and max.

min

A comparable minimum to limit the value to.

max

A comparable maximum to limit the value to.

返回值

clamp() returns the parameter value if considered "between" min and max according to standard comparisons.

If value is NAN, then the returned value will also be NAN.

错误/异常

If min is greater than max, clamp() throws a ValueError.

If min or max is NAN, clamp() throws a ValueError.

示例

<?php
echo clamp(-5, min: 0, max: 100), PHP_EOL;  // 0
echo clamp(55, min: 0, max: 100), PHP_EOL;  // 55
echo clamp(103, min: 0, max: 100), PHP_EOL;  // 100

echo clamp("J", min: "A", max: "F"), PHP_EOL;  // "F"

echo clamp(
    new \DateTimeImmutable('2025-08-01'),
    min: new \DateTimeImmutable('2025-08-15'),
    max: new \DateTimeImmutable('2025-09-15'),
)->format('Y-m-d'), PHP_EOL; // 2025-08-15
?>

参见

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。