Are there best practices for maintaining sort order in PHP when switching between different criteria?

When switching between different criteria for sorting data in PHP, it is important to maintain the sort order to ensure consistency and accuracy. One way to achieve this is by storing the current sort criteria and order in session variables, and then using these variables to apply the appropriate sorting when needed.

session_start();

// Check if sort criteria and order are set in session
if(isset($_SESSION['sort_criteria']) && isset($_SESSION['sort_order'])) {
    $sort_criteria = $_SESSION['sort_criteria'];
    $sort_order = $_SESSION['sort_order'];
    
    // Apply sorting based on stored criteria and order
    // Example: $sorted_data = sortData($data, $sort_criteria, $sort_order);
} else {
    // Default sorting criteria and order
    $sort_criteria = 'default_criteria';
    $sort_order = 'default_order';
    
    // Apply default sorting
    // Example: $sorted_data = sortData($data, $sort_criteria, $sort_order);
}

// Update session variables with new sort criteria and order
$_SESSION['sort_criteria'] = $new_criteria;
$_SESSION['sort_order'] = $new_order;