Alternative to if(x >= 200 && x <= 299)?

In PHP (or any similar language), is there a better alternative to:

if(x >= 200 && x <= 299){
   return 'ok';
}

My goal is to validate if a number is in the range of the 2xx code (for HTTP requests). I don't like the double-if clause because I must define the end of the range, and for some reason it's not practical when doing various automated validations.


Solution 1:

In PHP (or any similar language), is there a better alternative to...

No there isn't, in my opinion.

Your code:

if (x >= 200 && x <= 299) {
    return 'ok';
}

is very readable and clearly defines what is being checked.

Solution 2:

If you want a statement that you'll be sure to forget what you meant by it three months from now:

if(2 == (int)floor(x / 100)) ...

If nothing else, for readability's sake, wrap it in a function that describes it:

function isHttpSuccess(status) {
    return 2 == (int)floor(x / 100);
}

Solution 3:

If you have a function, you can use the return 'trick':

function getStatus(x) {
    if(x < 200) return 'status 1xx';
    if(x < 300) return 'status 2xx'; // will only get executed if x >= 200 as well
                                     // otherwise already returned '1xx'
    ...
}

Solution 4:

Wow this thread is over 10 years old! Adding another answer is probably just beating a dead horse (awful expression) but here goes...

The original question was about PHP but the code example provided looks like JavaScript. Here are some ideas for both languages (although the most upvoted answer is likely the best—just because we can do something doesn't mean we should)

In JavaScript, strings are objects that provide quick access to characters by index, so this could work:

if (x.toString()[0] === '2') {
    return 'ok';
}

If, instead of x we passed-in Response.status or similar, the concerns raised about legibility become somewhat moot:

if (Response.status.toString()[0] === '2') {
    return 'ok';
}

In PHP

if (substr($x, 0, 1) === '2') {
    return 'ok';
}

or

if (substr((string)$response->getStatusCode(), 0, 1) === '2') {
    return 'ok';
}

To take it further (maybe too far?) we can write a function to resolve status code "groupings"

const getStatusCodeGroup = (code) => {
  const groups = {
    '1': 'Informational responses (100–199)',
    '2': 'Successful responses (200–299)',
    '3': 'Redirection messages (300–399)',
    '4': 'Client error responses (400–499)',
    '5': 'Server error responses (500–599)'
  }
  return groups[code.toString()[0]] ?? 'Throw IRL';
}

Solution 5:

return in_array($code, range(200, 300));