[php] PHP If Statement with Multiple Conditions

I have a variable$var.

I want echo "true" if $var is equal to any of the following values abc, def, hij, klm, or nop. Is there a way to do this with a single statement like &&??

This question is related to php if-statement

The answer is


Try this piece of code:

$first = $string[0]; 
if($first == 'A' || $first == 'E' || $first == 'I' || $first == 'O' || $first == 'U') {
   $v='starts with vowel';
} 
else {
   $v='does not start with vowel';
}

You can try this:

<?php
    echo (($var=='abc' || $var=='def' || $var=='hij' || $var=='klm' || $var=='nop') ? "true" : "false");
?>

you can use the boolean operator or: ||

if($var == 'abc' || $var == 'def' || $var == 'hij' || $var == 'klm' || $var == 'nop'){
    echo "true";
}

I don't know if $var is a string and you want to find only those expressions but here it goes either way.

Try to use preg_match http://php.net/manual/en/function.preg-match.php

if(preg_match('abc', $val) || preg_match('def', $val) || ...)
   echo "true"

It will be good to use array and compare each value 1 by 1 in loop. Its give advantage to change the length of your tests array. Write a function taking 2 parameters, 1 is test array and other one is the value to be tested.

$test_array = ('test1','test2', 'test3','test4');
for($i = 0; $i < count($test_array); $i++){
   if($test_value == $test_array[$i]){
       $ret_val = true;
       break;
   }
   else{
       $ret_val = false;
   }
}

I found this method worked for me:

$thisproduct = "my_product_id";
$array=array("$product1", "$product2", "$product3", "$product4");
if (in_array($thisproduct,$array)) {
    echo "Product found";
}

you can use in_array function of php

$array=array('abc', 'def', 'hij', 'klm', 'nop');

if (in_array($val,$array))
{
  echo 'Value found';
}

An elegant way is building an array on the fly and using in_array():

if (in_array($var, array("abc", "def", "ghi")))

The switch statement is also an alternative:

switch ($var) {
case "abc":
case "def":
case "hij":
    echo "yes";
    break;
default:
    echo "no";
}

Dont know, why you want to use &&. Theres an easier solution

echo in_array($var, array('abc', 'def', 'hij', 'klm', 'nop'))
      ? 'yes' 
      : 'no';