Search code examples
phparraysstring-comparison

If a string is not matching one of 3 option in PHP


This is the code I used to have to check if $A doesn't match $B

if($A!=$B) {
    $set = array();
    echo $val= str_replace('\\/', '/', json_encode($set));
    //echo print_r($_SERVER);
    exit;
}

Now I need the opposite of this condition: ($A need to match one of these $B,$C or $D)


Solution

  • A simple shortcut to seeing if a value matches one of multiple values you can put the values to be compared against ($B, $C, and $D) into an array and then use in_array() to see if the original value ($A) matches any of them.

    if (in_array($A, [$B, $C, $D])) {
       // ...
    }
    

    If you don't want it to match any of $B, $C, or $D just use !:

    if (!in_array($A, [$B, $C, $D])) {
       // ...
    }