2

In my code, I fill an array using this line in a loop :

 $_SESSION['my_array'][] = $some_value;

After each execution of this line, I do some check (doesn't matter here for which purpose) using the function in_array(). However, at the first iteration it says :

« in_array() expects parameter 2 to be array ».

How to fix this problem?

1
  • 1
    Can we see the code where you are doing in_array()? Commented Apr 22, 2013 at 11:04

3 Answers 3

3

You can initialize the array (before you fill it with values) like this:

$_SESSION['my_array']=array();

This way you can be sure that it is array, even when it would be empty.

Sign up to request clarification or add additional context in comments.

Comments

0

You are assigning or accesing it wrongly

Use this

$_SESSION['my_array'] = $some_value;

Comments

0

When you are doing the in_array check, you can cast the second item to an array, so if it's empty then it will pass an empty array. This way you don't ever set anything to the session when you don't need to (which could trip you up later on)

e.g.,

if (in_array('foo', (array)$_SESSION['my_array'])) {
  // do something
}

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.