簡體   English   中英

如果帶或(||)參數的語句不適用於in_array方法

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

我有這段代碼

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

即使我寫了一個在array1或array2中都存在的正確值,我也會因throw new \\ Exception引發錯誤。

如果我刪除了if語句中的or子句並輸入了正確的值,則不會發生任何錯誤,但是我無法檢查第二個條件。

我的if陳述在哪里錯?

您需要使用邏輯,而(&&)不能或。 你是說

如果$ slug不在array1或不在數組2中,則引發異常。 因此,為避免引發異常,子彈值必須同時在數組1和數組2中。

您真正想要的(我假設)是,如果slug的值不在兩個數組中,則拋出異常,但是如果它存在於一個數組中,則不執行任何操作並繼續執行。 因此,將您的if語句更改為:

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

當您要檢查時,如果2個條件為真,則使用and(&&)的邏輯運算符。或運算符(||)將檢查其中一個是否為真。請記住布爾代數,以免丟失軌跡。

要么:

statment1=true;
statment2=false;
if(statment1=true||statment2=true){do stuff}//it will run because at least one statment is true

和:

statment1=true;
statment2=false;
if(statment1=true && statment2=true){do stuff}//it wont run because both statments must be true.
if (!in_array($slug, $array1) || !in_array($slug, $array2))

如果數組之一中不存在value,則此條件將引發異常。 因此,如果您的值存在於一個數組中而不存在於另一個數組中,則將引發異常。

在Wikipedia上查看此邏輯分離表: https//en.wikipedia.org/wiki/Truth_table#Logical_disjunction_.28OR.29

您必須使用and運算符:

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

如果您的意思是如果$slug存在於任何數組中,那么您不希望引發錯誤,則應使用&&

if (!in_array($slug, $array1) && !in_array($slug, $array2))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM