What are some common pitfalls to avoid when working with session variables and arrays in PHP?

One common pitfall when working with session variables and arrays in PHP is directly assigning an array to a session variable without initializing it first. This can lead to unexpected behavior or errors when trying to access or manipulate the array later on. To avoid this, always initialize the session variable as an empty array before adding elements to it.

// Incorrect way - directly assigning an array to a session variable
$_SESSION['myArray'] = ['apple', 'banana', 'orange'];

// Correct way - initialize session variable as an empty array first
$_SESSION['myArray'] = [];
$_SESSION['myArray'][] = 'apple';
$_SESSION['myArray'][] = 'banana';
$_SESSION['myArray'][] = 'orange';