nkcmr
nkcmr

Reputation: 11010

Testing multiple values efficiently in PHP

Okay, so I have a few possible matches that I need to test. It can either equal A or B, so the obvious way to test it would be something like this:

if($val=="A"||$val="B"){
    echo "yup";
}

I was just wondering if their were an easier way to test values without restating the variable for every value, like this (I know this doesn't work):

if($val==("A"||"B")){
    echo "yuppers";
}

Is something like this possible?

Upvotes: 1

Views: 783

Answers (3)

haynar
haynar

Reputation: 6030

you can add "A" and "B" to the array and use in_array method but this is definitely not more efficient than $val=="A" || $val =="B"

Upvotes: 2

Wouter J
Wouter J

Reputation: 41934

You can use in_array:

if (in_array($val, array('A', 'B'))) {
    echo 'yuppest';
}

Upvotes: 3

Marcus Recck
Marcus Recck

Reputation: 5063

You can use in_array

$array = array('A','B','other values');
if(in_array($val, $array)){
    // value is in array
}else {
    // invalid value
}

Upvotes: 8

Related Questions