5

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?

user151841
  • 17,377
  • 29
  • 109
  • 171

3 Answers3

11

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

Narcissus
  • 3,144
  • 3
  • 27
  • 40
1

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
  • 312,688
  • 75
  • 539
  • 559
  • Why bothering ORing? A simple `$var &= 0xFF` will mask the value to a 0-255 range – Marc B Apr 29 '10 at 17:52
  • @MarcB what's *bothering* about using OR? – Gordon Apr 29 '10 at 19:31
  • Marc B's answer makes sense - I don't get what Gordon's trying to achieve. – symcbean Apr 29 '10 at 22:07
  • 1
    @symcbean using `$var &= 0xFF` to flip the value over makes as much sense as OR'ing `$num` to validate it's between 0 and 255 (which is what my code does). Both approaches are not the equivalent to the OPs `if` block to which @Narcissus already gave a one-liner, but alternate approaches to the problem. – Gordon Apr 29 '10 at 22:39
  • @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 Apr 30 '10 at 18:32
  • @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 Apr 30 '10 at 19:55
0

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

eg.

( ($num > 255) ? 255 : ( ($num < 0) ? 0 : $num) )
Jonathon Vandezande
  • 2,446
  • 3
  • 22
  • 31