phparraysif-statement

If statement with or (||) argument does not work with in_array method


I have this snippet of code:

public function dynamicSlugAction(Request $request, $slug)
{
    $array1 = ["coffee", "milk", "chocolate", "coca-cola"];
    $array2 = ["water", "juice", "tomato-juice", "ice-tea"];
    if (!in_array($slug, $array1) || !in_array($slug, $array2)) {
        throw new \Exception("The var " . strtoupper($slug) . " is not exist with parameter (slug): " . $slug);
    }
}

Even if I write a right value which exist in array1 or array2 I have the error launched by the throw new \Exception.

If I remove the or clause in the if statement and I write a right value, no error occurred but I can't check the second condition.

Where am I wrong in my if statement?


Solution

  • You need to use logical and (&&) not or. You are saying

    If $slug isn't in array1 or isn't in array 2, throw the exception. So to not throw the exception the slug value would need to be in BOTH array 1 and array 2.

    What you really want (I assume), if that if the value of slug isn't in either array throw the exception, but if it exists in one of the arrays, do nothing and carry on. So change your if statement to:

    if (!in_array($slug, $array1) && !in_array($slug, $array2)) {
      throw new \Exception("The var ".strtoupper($slug)." is not exist with parameter (slug): ".$slug);
    }