0

Possible Duplicate:
php if integer between a range?

Let's say $num = 5; How do I test if $value is anything in between +-3 of $num. In other words, how can I test if $value is equal to any of these values 2,3,4 5 6,7,8

Community
  • 1
  • 1
sameold
  • 18,400
  • 21
  • 63
  • 87

6 Answers6

9

Two possible ways to do it:

  1. $num - 3 <= $value && value <= $num + 3
  2. abs($num - $value) <= 3
Lie Ryan
  • 62,238
  • 13
  • 100
  • 144
2
$mid = 5;
$range = 3;
$inRange = ($myval>=$mid-$range && $myval<=$mid+$range) ? TRUE : FALSE;

UPDATE I started throwin' out bass, she started throwin' back mid-range.

  • Nobody else appreciated my **sweet** unintentional Biz Markie reference, I guess :) –  Jan 20 '12 at 08:57
1
if ($num - 3 <= $value && $value <= $num + 3)
deceze
  • 510,633
  • 85
  • 743
  • 889
1
if ($value<=$num+3 && $value>=$num-3)
    echo "$value is between +-3 of $num";
else
    echo "$value is outside +-3 of $num";
rauschen
  • 3,956
  • 2
  • 13
  • 13
1

try this:

$dif1 = $num - 3;
$dif2 = $num + 3;

if($dif1 <= $value){
       if($dif2 <= $value){
              echo "Your number in between +-3";
       }  
}
Kichu
  • 3,284
  • 15
  • 69
  • 135
0

There is nothing big logic in this if you know the $num value take two variable $min and $max

set $min = $num - 3

set $max = $num + 3

and then with condition check your value..

$value > $min && $value < $max

Murtaza
  • 3,045
  • 2
  • 25
  • 39