"php check value against multiple values with or-operator" Answer’s


The logical ||(OR) operator doesn't work as you expect it to work. The || operator always evaluates to a boolean either TRUE or FALSE. So in your example your strings get converted into booleans and then compared.

If statement:

if($ext == ('txt' || 'rtf'|| 'log' || 'docx'))

Comes down to:

if($ext == (TRUE || TRUE || TRUE || TRUE))
if($ext == TRUE)

To solve this problem and get the code to work as you want it to you can use different methods.

Multiple comparison

One way to solve the problem and check your values against multiple values is, to actually compare the value against multiple values:

if($ext == "txt" || $ext == "rtf" /* || ... */)


Another way is to use the function in_array() and check if the value is equal to one of the array values:

if(in_array($ext, ["txt", "rtf" /* , ... */], TRUE))

Note: Second parameter is for strict comparison


You could also use switch to check your value against multiple values and just let the case fall through.


    case "txt":
    case "rtf":
 /* case ...: */
        $pClass = "text-";

Wednesday, March 31, 2021
answered 10 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :