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

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

You can try this:

    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";
    echo "no";

Meet with owner

Sajjad Hossain

Hey, I am Sajjad, working in web development sector since 2012. I love to do amazing things. Let's do a project together.
Connect Social With PHPAns