What are the potential pitfalls of using unset() in PHP sessions when trying to delete specific items from an array?

When using unset() to delete specific items from an array stored in a PHP session, the key of the item being unset will be removed, but the remaining keys will not be reindexed. This can lead to unexpected behavior when iterating over the array. To solve this issue, you can use array_values() to reindex the array after unsetting the item.

// Initialize session if not already started
session_start();

// Check if the item exists in the session array
if (isset($_SESSION['array'][$key])) {
    // Unset the item
    unset($_SESSION['array'][$key]);
    // Reindex the array
    $_SESSION['array'] = array_values($_SESSION['array']);
}