Jump to content

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.

you can simplify that frost...

 

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

 

Doesn't the <> mean not equal to three ??? Or am I mistaken, if so he said he would like to include three in his reply...

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.