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, a non-numeric string will be compared to an int as though it were 0, but multiple non-numeric string values will be compared alphanumerically. 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"

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
?>

Π‘ΠΌΠΎΡ‚Ρ€ΠΈΡ‚Π΅ Ρ‚Π°ΠΊΠΆΠ΅

  • min() - Находит наимСньшСС Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅
  • max() - Π’ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ наибольшСС Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅
οΌ‹Π”ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ

ΠŸΡ€ΠΈΠΌΠ΅Ρ‡Π°Π½ΠΈΡ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ

ΠŸΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΠΈ Π΅Ρ‰Ρ‘ Π½Π΅ добавляли примСчания для страницы