Jump to content

simple more than less than if statement (i think)


c_shelswell

Recommended Posts

Frying my brain a bit trying to figure this out. I'm sure it's very easy though.

 

I'm just trying to make a simple more than or less than statement but i'm sure there's a better way than the way i'm doing it:

 


$y = 3;

if ($y== 1||$y==2|| $y == 3 || $y == 4 || $y==5)
{
     do something
}

 

so i'm just trying to make the "if" go 2 either side of 3. Is there a better way than writing it in such a long way?

 

Thanks 

sorry should have said "2 either side of 3 and inclusive of 3"

 

Cheers

 

<?php
$y=3;
if (($y < 3 || $y>=3) && ($y>0 && $y<6)) {
    echo 'here we are';
}
?>

 

Not sure if that is any better than the original statement but should work.

Just because I am bored, if you wanted this to be very versatile you could do something like this:

 

<?php
function within($num, $within=3, $within_what=2) {
       $upper = $within_what + $within;
       $lower = $within_what - $within;
       
       $x;
       for ($i=$within;$i<$upper;$i++) {
             if ($i == $num) {
                 return true;
            }elseif ($x == $num) {
                 return tre;
            }
       }
       
       return false;
}

$y = 4;
if (within($y)) {
     echo 'yep';
}

$y=7;
if (!within($y, 3, 2)) {
     echo 'nope';
}

$y=3;
if (within($y)) {
     echo 'yep';
}
?>

 

Just something fun to do if you are going to be using this quite a bit.

<?php
function within($num, $within=3, $within_what=2) {
       $upper = $within_what + $within;
       $lower = $within_what - $within;

       if($num < $lower || $num > $upper) {
             return true;
       }else {
             return false;
       }
}

$y = 4;
if (within($y)) {
     echo 'yep';
}

$y=7;
if (!within($y, 3, 2)) {
     echo 'nope';
}

$y=3;
if (within($y)) {
     echo 'yep';
}
?>

 

Thanks to av1611 for providing that, made the function less processing intense. =) Updated the function without the for loop.

Archived

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

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.