开发者

PHP: How can I determine if a variable has a value that is between two distinct constant values?

How can I determine using PHP code that, 开发者_如何学Gofor example, I have a variable that has a value

  • between 1 and 10, or
  • between 20 and 40?


if (($value > 1 && $value < 10) || ($value > 20 && $value < 40))


Do you mean like:

$val1 = rand( 1, 10 ); // gives one integer between 1 and 10
$val2 = rand( 20, 40 ) ; // gives one integer between 20 and 40

or perhaps:

$range = range( 1, 10 ); // gives array( 1, 2, ..., 10 );
$range2 = range( 20, 40 ); // gives array( 20, 21, ..., 40 );

or maybe:

$truth1 = $val >= 1 && $val <= 10; // true if 1 <= x <= 10
$truth2 = $val >= 20 && $val <= 40; // true if 20 <= x <= 40

suppose you wanted:

$in_range = ( $val > 1 && $val < 10 ) || ( $val > 20 && $val < 40 ); // true if 1 < x < 10 OR 20 < x < 40


You can do this:

if(in_array($value, range(1, 10)) || in_array($value, range(20, 40))) {
   # enter code here
}


if (($value >= 1 && $value <= 10) || ($value >= 20 && $value <= 40)) {
   // A value between 1 to 10, or 20 to 40.
}


Guessing from the tag 'operand' you want to check a value?

$myValue = 5;
$minValue = 1;
$maxValue = 10;

if ($myValue >= $minValue && $myValue <= $maxValue) { 
  //do something
}


Sorry for the late answer, but this function allow you to do that.

  function int_between($value, $start, $end) {
    return in_array($value, range($start, $end));
  }

  // Example
  $value1 = 20;
  $value2 = 40;
  echo int_between(20, $value1, $value2) ? "true" : "false";


If you just want to check the value is in Range, use this:

   MIN_VALUE = 1;
   MAX_VALUE = 100;
   $customValue = min(MAX_VALUE,max(MIN_VALUE,$customValue)));


Try This

if (($val >= 1 && $val <= 10) || ($val >= 20 && $val <= 40))

This will return the value between 1 to 10 & 20 to 40.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜