tags:

views:

55

answers:

3

This is what i have currently

if($j == 1 || $j == 2 || $j == 3)

Is there a simpler way of writing this. Something like...

pseudocode

if($j == 1-3)
+4  A: 

Here's one way using in_array()

if (in_array($j, array(1,2,3)))
{
    //do something
}

Or how about using range() to make the array

if (in_array($j, range(1,3)))
{
    //do something
}

However, building an array just to check a narrow, contiguous range like that is pretty inefficient. So how about simply:

if ($j >= 1 && $j <= 3)
{
    //do something
}

If other values of $j will trigger different action, a switch might be more appropriate...

switch($j)
{
    case 1:
    case 2:
    case 3:
        //do something
        break;        

}
Paul Dixon
+3  A: 

If it's a range, you can simply do:

if ($j >= 1 && $j <= 5) ...
reko_t
+1 of course for large this is better than my example
Michal M
+1  A: 

Paul's good one, but if you have a large number then you may want to use range:

if (in_array($j, range(0, 100)))
{

}
Michal M
reko_t