Reputation: 10117
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)
Upvotes: 2
Views: 1294
Reputation: 300835
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;
}
Upvotes: 7
Reputation: 9480
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)))
{
}
Upvotes: 1