Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple comparison operators for one variable?

Tags:

php

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?

like image 314
A Smith Avatar asked Jul 23 '26 14:07

A Smith


1 Answers

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
}
like image 187
VisioN Avatar answered Jul 25 '26 03:07

VisioN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!