What are the best practices for maintaining the order of values stored in a subarray within $_SESSION in PHP?

When storing values in a subarray within $_SESSION in PHP, it's important to maintain the order of the values to ensure data integrity. To achieve this, you can use numeric keys in the subarray and update them accordingly when adding or removing values. By keeping track of the order using numeric keys, you can preserve the sequence of values stored in the subarray.

// Start or resume the session
session_start();

// Initialize the subarray if it doesn't exist
if (!isset($_SESSION['subarray'])) {
    $_SESSION['subarray'] = array();
}

// Add a new value to the subarray with a numeric key
$_SESSION['subarray'][] = 'Value 1';
$_SESSION['subarray'][] = 'Value 2';

// Remove a value from the subarray by key
unset($_SESSION['subarray'][0]);