What is the best practice for dynamically generating sorting links in PHP?

When dynamically generating sorting links in PHP, it is best practice to use a combination of query parameters and conditional statements to determine the sorting order. By passing the sorting criteria as a query parameter in the URL, you can easily adjust the sorting order without modifying the code. This allows for flexibility and reusability in your sorting functionality.

<?php
$sortBy = isset($_GET['sort']) ? $_GET['sort'] : 'default';

function generateSortLink($field) {
    $currentSort = isset($_GET['sort']) ? $_GET['sort'] : 'default';
    $newSort = ($currentSort == $field && $currentSort[0] != '-') ? '-' . $field : $field;
    
    return http_build_query(array_merge($_GET, ['sort' => $newSort]));
}

echo '<a href="?'.generateSortLink('name').'">Sort by Name</a>';
echo '<a href="?'.generateSortLink('date').'">Sort by Date</a>';
?>