开发者

unsigned tinyint in php?

开发者 https://www.devze.com 2022-12-28 10:16 出处:网络
I\'m working on a class to manipulate html hex color codes in php. Internally, the class treats RGB values as decimals. When I\'m adding or subtracting, I never want the value to exceed 255 nor \'subc

I'm working on a class to manipulate html hex color codes in php. Internally, the class treats RGB values as decimals. When I'm adding or subtracting, I never want the value to exceed 255 nor 'subceed' zero.

If course, I can do something piecemeal like

if ( $val >  255 ) {
    $val = 255;
} 
if ( $val < 0 ) {
    $val = 0;
}

But that's verbose :P

Is there 开发者_StackOverflow中文版a clever, one-linish way I can get the value to stay between 0 and 255?


You could possibly say something like: $val = max(0, min(255, $val));


Using the bitwise OR operator would work

if(($num | 255) === 255) { /* ... */ }

Example:

foreach (range(-1000, 1000) as $num) {
    if(($num | 255) === 255) {
        echo "$num, ";
    };
}

would print out all the numbers from 0 to 255.


Or you could be that guy who uses nested ternary operators.

eg.

( ($num > 255) ? 255 : ( ($num < 0) ? 0 : $num) )
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号