0

I have and array, and I want to convert it into an if conditional.

$array = ['check 1', 'check 2', 'check 3'];

I want the final result to work like this:

if ($var == 'check 1' || $var == 'check 2' || $var == 'check 3') {
    // Do here.
}

I don't have any inspiration, I already searched for convert array to if condition but I couldn't find anything.

How can I convert the array into an if conditional?

8
  • 3
    in_array can be useful to you Commented Dec 7, 2017 at 10:59
  • but, how to check multiple value if i use in_array Commented Dec 7, 2017 at 11:00
  • Loop array. Check value of current iteration of the loop. Commented Dec 7, 2017 at 11:00
  • 3
    if (in_array($var, $array) || in_array($var1, $array)){ //do something } Commented Dec 7, 2017 at 11:02
  • Where is the array? I cannot see any array in the code you posted. Commented Dec 7, 2017 at 11:17

3 Answers 3

4

Instead of multiple || (OR) conditions use in_array()

if (in_array($var, $array)) {
    // do here
}

Output:-https://eval.in/914346

If you want to check multiple variables against array then do like this:-

if (in_array($var, $array) || in_array($var1, $array)){ 
  //do here
}

Output:- https://eval.in/914351

Note:- If you can clarify more about all your variables and what conditions you want for all those variables, you will get more accurate answer

Sign up to request clarification or add additional context in comments.

Comments

1

Loop through array and check in_array like this:

$array = ( 'check 1', 'check 2', 'check 3' );

    foreach($array as $k => $v)
    {
        $flag = "false";
        if(in_array($v,$array))
        {
            $flag = "true";
        }
    }

So from above code, is any of the value exist in array, the variable $flag will have string value "true".

Comments

1
<?php

$array = array( "mango", "grapes","apple");
//let you have to find apple

if(in_array('masngo',$array) || in_array('mango',$array)){
    echo "FIND";
    //OR WHATEVER YOU WANT TO DO
}else{
    echo "Not Found";
}

Try to run HERE

1 Comment

This won't be a generic solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.