PHP If Statement with Multiple Conditions

    |
  • Added:
  • |
  • In: Basic PHP

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 Has 8 Answeres | Orginal Question | blasteralfred ?

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 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" 

You can try this:

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

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

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

you can use in_array function of php

$array=array('abc', 'def', 'hij', 'klm', 'nop'); if (in_array($val,$array)) { echo 'Value found'; } 
if($var == "abc" || $var == "def" || ...) { echo "true"; } 

Using "Or" instead of "And" would help here, i think

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"; } 

Search
I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.

Connect Social With PHPAns
Top