In php, how do you say if ($ x == 1 or 2 or 3 or 4) {do function} without repeating the code many times?

I am not very good at php and I could do with a little help. I want to say something like

if ($x == 1 or 2 or 3 or 4) {do function}


but the only way i know how to do it is to go

if (($x == '1') or ($x == '2')) or...


which seems like a long way to do it. Is there a better way that I am overlooking like

if ($x == 1,2,3,4) {do} 


Thank you for your responses!


source to share

6 answers

you can use in_array function

$array = array(1,2,3,4)

if(in_array($x, $array)) {
    // do something




switch ($x) {
    case 1:
    case 2:
    case 3:
    case 4:
        // do


Or you can use a function in_array()

that creates an array like $a = array(1,2,3,4);

and then do if (in_array($x, $a))


If you are concerned about whitespace, you can also use a shortcut:

if (in_array($x, array(1,2,3,4))) { /* do */ }




You can create an array of expected values ​​and then use the in_array () function.



If it's a range, you can do:

if ($x >= 1 && $x <= 4) { }


You can also build an array and check if the number is in that array.



    $data = array(1,2,3,4);
    if(in_array($x, $data)){
        // execute function




All of the above ideas are good. I'm going to show you another way, which is not better, but different.

You can store comparisons in variables, use them later, or combine them. It helps readability and makes it easier to create and read complex expressions. He obviusly removed any repetition.

$is_number = ($str=="one" or $str=="two" or $str=="tree");
$is_english = ($str=="one" or $str=="horse");
$is_french = ($str=="baguette" or $str=="amie");
$is_fun = $is_french or $is_english;

if($is_french and !$is_number){ ... } 




All Articles