0

How can I optimize this if-statement?

if ($min && $max && $value && ($min <= $max) && ($min <= $value) && ($value <= $max)) {
    // do anything
}

What it should do:

I got three values (min, max and value). First of all, all values should be != 0. Second, min <= value <= max.

Valid:

min = 1; max = 3; value = 2;
min = 2; max = 2; value = 2;
user3142695
  • 15,844
  • 47
  • 176
  • 332
  • 1
    I don't see much need to optimize this, as it is composed of simple boolean comparisons. It's readable and clear in its current form. – Michael Berkowski Oct 12 '14 at 18:03
  • (edited comment about zero values - you already mention that and address it correctly) – Michael Berkowski Oct 12 '14 at 18:05
  • 1
    You can remove the check for `($min <= $max)`, as you are indirectly checking for this with `($min <= $value) && ($value <= $max)`. – Terry Oct 12 '14 at 18:05
  • Ok, thanks. I thought this statement is a little bit long. – user3142695 Oct 12 '14 at 18:06
  • 1
    Whenever you feel an `if` condition chain gets too long, a function can make sense; see also [if integer between a range?](http://stackoverflow.com/q/5029409) – mario Oct 12 '14 at 18:07

3 Answers3

2

this:

if ( 0 < $min && $min <= $value && $value <= $max ){
    echo 'good';
}
Ben
  • 149
  • 10
1

The answer is:

if(isset($min , $max , $value ) && ($min <= $value) && ($value <= $max)){
//Insert your code here
}
4EACH
  • 2,132
  • 4
  • 20
  • 28
0

I think this prevents any value from being a 0 and makes sure value is inside the min and max range.

if ( ( $min > 0 && $max >= $min ) && ( $value >= $min && $value <= $max ) ) {
  echo "Good";
} else {
  echo "Bad";
}
Victor Tello
  • 161
  • 13