PHP: Constrains a value to not exceed a maximum and minimum value

幾年前在寫 Processing (P55) 的時候,有個方便的 function 叫 constrain。用法是

constrain(value, min, max)

例如

float mx = constrain(mouseX, 30, 70);

當 mouseX 大於 70 時就回傳 70,小於 30 時就回傳 30,將值限制在 30 ~ 70 這個區間。因為 Processing 大都是拿來寫互動、視覺方面的程式,所以用到此功能的頻率頗高。後來轉換跑道寫其他語言時,發現好像都沒有這個方便的函式。
最近又有 constrain 的需求,想起幾年前見過有人用 min, max 來代替,寫法如下。

<?php
function constrain($value, $min, $max){
    return max( min( $value, $max), $min);
}

echo constrain(29.3, 30, 60);
?>

Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Exit mobile version