Unsigned tinyint in php?

I am working on a class to manipulate html hex color codes in php. Internally, the class treats RGB values ​​as decimal numbers. When I add or subtract, I never want the value to exceed 255, but not "start" from scratch.

Unless, of course, I can do something piecemeal

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

But this one is detailed: P

Is there a smart, single-line way, can I make the value stay from 0 to 255?

+5
source share
3 answers

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

+11
source

Using the bitwise OR operator will work

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

Example:

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

0 255.

+1

, .

.

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

All Articles