4

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.

4
  • 1
    it seems $_SESSION['product'] dosen't contain any data. Try to print $_SESSION['product'] Commented Jan 10, 2017 at 9:19
  • 2
    $_SESSION['product'] is null Commented Jan 10, 2017 at 9:20
  • may i know which one return an array $_SESSION['product'] or $_GET['product'] ? Commented Jan 10, 2017 at 9:23
  • Add a $_SESSION["product"] = $_SESSION["product"]?:[] before the if to initialize the array. Otherwise you'll never add anything to it with this code. Commented Jan 10, 2017 at 9:23

4 Answers 4

4

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'];
    }
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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'];
}

Comments

1

you should always apply check for array

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.