2017-01-10 64 views
1

嘗試向會話添加數據(並檢查它是否已存在)時,出現以下警告。警告:in_array()期望參數2爲數組,空給出

警告:in_array()預計參數2是數組,空給出

我該如何解決這個問題?

它指的是代碼:

if(isset($_GET['product']) && !in_array($_GET['product'], $_SESSION['product'])){ 
    $_SESSION['product'][] = $_GET['product']; 
} 

在清潔的瀏覽器中添加的第一個產品的時候,我只得到這樣的警告。當我刪除它並添加另一個產品時,警告消失了。同樣如果我添加第二個產品。

+1

似乎'$ _SESSION [ '產品']'這麼想的包含任何數據。嘗試打印'$ _SESSION ['product']' –

+2

'$ _SESSION ['product']'爲空 –

+0

我可以知道哪一個返回數組$ _SESSION ['product']或$ _GET ['product']? –

回答

2

警告說這一切。此參數爲空:

$_SESSION['product'] 

確保在使用它之前設置它。例如:

if(isset($_SESSION['product']) && isset($_GET['product']) && !in_array($_GET['product'], $_SESSION['product'])){ 
     $_SESSION['product'][] = $_GET['product']; 
    } 
+0

謝謝,簡單的解決方案:)我會在10分鐘內接受。 – twan

+0

@twan很高興我能幫忙:) – malutki5200

1

您的$_SESSION['product']爲空。 試試這個,

if(!empty($_SESSION['product']) && isset($_GET['product']) && !in_array($_GET['product'], $_SESSION['product'])){ 
    $_SESSION['product'][] = $_GET['product']; 
} 

它應該工作。

1

檢查該值是否在與isset一起使用之前設置,並使用is_array檢查給定變量是否爲數組。

if(isset($_GET['product']) && is_set($_SESSION['product']) && is_array($_SESSION['product']) && !in_array($_GET['product'], $_SESSION['product'])){ 
    $_SESSION['product'][] = $_GET['product']; 
} 
0

你應該總是申請支票陣列

isset($_SESSION['product']) in your is condition before & condition 
相關問題