Jump to content

checking for a value in a range


real_illusions

Recommended Posts

Hi all,Probably a pretty straight forward question.Is there a simple comparion operator (or similiar) that can check if a value is between 2 sets. So to check if a variable (always a number) is between 2 and 15 for example.Thanks :)

Link to comment
Share on other sites

you can use range to create a set of arraythen you can use in_array to check certain value exist or not.

$rset=range(2,15);if(in_array(5,$rset))echo "it is here";else"echo it is not";

you can add any other valuse also like$rset[]=23;

Link to comment
Share on other sites

You can do a sort of minor optimization if you swap your if/else branches, and use || instead, like:

if ($x < 2 || $x > 15) {//if the number is NOT in the range}else {//if the number IS in the range}

This only works in that scenario though (you're trading three constant operators for two best, three worst)... if you're to keep your branches as with the &&, you need to use "!" over the whole thing, at which point the minor optimization is lost (you're trading three constant operators for another three operators best, four operators worst).

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...