警告:in_array()期望参数2为数组,给定为null
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.
尝试向会话添加数据时(我检查它是否已存在),我收到以下警告。 / p>
警告:in_array()期望参数2为数组,给定为空 p> blockquote>
我如何修复 这个? p>
它所指的代码: p>
if(isset($ _ GET ['product'])&& !in_array($ _ GET ['product'],$ _SESSION ['product'])){ $ _SESSION ['product'] [] = $ _GET ['product']; } code> pre>
我只在清理过的浏览器上添加第一个产品时收到此警告。 当我删除它并添加另一个产品时,警告消失了。 如果我添加第二个产品,则相同。 p> div>
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'];
}
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.
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'];
}
you should always apply check for array
isset( $_SESSION['product']) in your is condition before & condition