A Smith
A Smith

Reputation: 237

Multiple comparison operators for one variable?

I need to do multiple checks for a variable. I've seen an "Equals" example, here: w3schools. But they are two different variables. Right now I have:

if ($color == 'blue')
{
//do something
}

But I need to to multiple checks for $color. Eg if it equals red or green too. How is this written?

Upvotes: 2

Views: 9077

Answers (3)

TCB13
TCB13

Reputation: 3155

You can also go with preg_match on this one. This might be overkill, but I'm sure it's very fast!

$color = "blue";
$pattern = "/^red|blue|yellow$/";
if ( preg_match($pattern,$color) ) { 
    // Do something nice here!
} 

Upvotes: 0

VisioN
VisioN

Reputation: 145398

As simple as:

if ($color == 'blue' || $color == 'red' || $color == 'green') {
    //do something
}

There are several other options. Using switch operator:

switch ($color) {
    case 'blue':
    case 'red':
    case 'green':
        //do something
}

Or more complex using in_array function:

$colors = array('blue', 'red', 'green');
if (in_array($color, $colors)) {
    //do something
}

Upvotes: 9

Kep
Kep

Reputation: 5857

Use a switch-statement.

switch($color)
{
    case "blue":
        // do blue stuff
        break;
    case "yellow":
        // do yellow stuff
        break;
    case "red":
        // do red stuff
        break;
    default:
        // if everything else fails...
}

In case you want to do the same thing on all colors, just use the || (boolean or) operator.

if ($color == "blue" || $color == "red" || $color == "yellow")
{
     // do stuff
}

Upvotes: 2

Related Questions