views:

138

answers:

2

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 a clever, one-linish way I can get the value to stay between 0 and 255?

+7  A: 

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

Narcissus
+1  A: 

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.

Gordon
Marc B
@MarcB what's *bothering* about using OR?
Gordon
Marc B's answer makes sense - I don't get what Gordon's trying to achieve.
symcbean
Gordon
@gordon. Sorry, typo. Meant "why bother with". But consider that this filtered number may need to be used elsewhere. Your version guaratees a maximum of 255, but also forces everything to be 255. Using the bit-wise AND leaves the number in a usable state.
Marc B
@MarcB it's not forcing anything to be 255. It either is or is not. Mine is a mere validation, while yours is a transformation. I'd say both is fine, depending on the use-case.
Gordon