french_dev french_dev - 23 days ago 6
PHP Question

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

I have this function in my symfony controller:

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 wich exist in array1 or array2 I have the error launch by the throw new \Exception.

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

Where am I wrong in my if statement ?


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);