What are some best practices for initializing and working with arrays in PHP sessions?

When working with arrays in PHP sessions, it's important to properly initialize them to avoid errors and ensure smooth functionality. To do this, you can check if the array exists in the session before accessing or modifying it. If it doesn't exist, you can initialize it as an empty array.

// Start the session
session_start();

// Check if the array exists in the session
if (!isset($_SESSION['my_array'])) {
    $_SESSION['my_array'] = [];
}

// Access or modify the array as needed
$_SESSION['my_array'][] = 'new_element';