Warning: in_array() expects parameter 2 to be array, null given

天大地大妈咪最大 提交于 2021-02-04 19:49:08

问题


I am getting the following warning when trying to add data to a session (and checking if it already exists).

Warning: in_array() expects parameter 2 to be array, null given

How can I fix this?

The code it is referring to:

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

I only get this warning when adding the first product on a cleaned browser. When I remove it and add another product the warning is gone. Same if I add a second product.


回答1:


The warining says it all. This param is null:

 $_SESSION['product']

Make sure it is set before you use it. Example:

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



回答2:


Your $_SESSION['product'] is empty. Try this,

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

It should work.




回答3:


check if the value is set before use it with isset and use is_array to check if a given variable is an array.

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



回答4:


you should always apply check for array

isset( $_SESSION['product']) in your is condition before & condition 


来源:https://stackoverflow.com/questions/41565184/warning-in-array-expects-parameter-2-to-be-array-null-given

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!