mrpatg
mrpatg

Reputation: 10117

Is there a simpler way to check if a variable equals a variety of numbers?

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

Answers (3)

Paul Dixon
Paul Dixon

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

Michal M
Michal M

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

reko_t
reko_t

Reputation: 56430

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

if ($j >= 1 && $j <= 5) ...

Upvotes: 4

Related Questions