What are some best practices for handling and manipulating arrays in PHP, especially within sessions?

When handling and manipulating arrays in PHP, especially within sessions, it is important to properly serialize and unserialize the arrays to store them in session variables. This ensures that the data is stored and retrieved correctly without losing any information. Additionally, it is recommended to check if the array exists in the session before manipulating it to avoid errors.

// Start the session
session_start();

// Check if the array exists in the session
if(isset($_SESSION['my_array'])) {
    // Retrieve the array from the session and unserialize it
    $myArray = unserialize($_SESSION['my_array']);

    // Manipulate the array as needed
    $myArray[] = 'new element';

    // Serialize the array and store it back in the session
    $_SESSION['my_array'] = serialize($myArray);
} else {
    // Initialize the array if it doesn't exist
    $myArray = [];
    $myArray[] = 'new element';

    // Serialize the array and store it in the session
    $_SESSION['my_array'] = serialize($myArray);
}