How can PHP be used to sort data in a dynamic table based on user click?

To sort data in a dynamic table based on user click, you can use PHP to dynamically generate the table with sorting links that pass sorting parameters through the URL. The PHP script will then retrieve these parameters, sort the data accordingly, and display the sorted table.

<?php
// Sample data array
$data = array(
    array('id' => 1, 'name' => 'Alice', 'age' => 25),
    array('id' => 2, 'name' => 'Bob', 'age' => 30),
    array('id' => 3, 'name' => 'Charlie', 'age' => 22)
);

// Get sorting parameters from URL
$sortBy = isset($_GET['sort_by']) ? $_GET['sort_by'] : 'id';
$sortOrder = isset($_GET['sort_order']) ? $_GET['sort_order'] : 'asc';

// Function to compare values for sorting
function cmp($a, $b) {
    global $sortBy, $sortOrder;
    return ($sortOrder == 'asc') ? ($a[$sortBy] > $b[$sortBy]) : ($a[$sortBy] < $b[$sortBy]);
}

// Sort data based on sorting parameters
usort($data, 'cmp');

// Display table with sorted data
echo '<table>';
echo '<tr><th><a href="?sort_by=id&sort_order=' . ($sortBy == 'id' ? ($sortOrder == 'asc' ? 'desc' : 'asc') : 'asc') . '">ID</a></th><th><a href="?sort_by=name&sort_order=' . ($sortBy == 'name' ? ($sortOrder == 'asc' ? 'desc' : 'asc') : 'asc') . '">Name</a></th><th><a href="?sort_by=age&sort_order=' . ($sortBy == 'age' ? ($sortOrder == 'asc' ? 'desc' : 'asc') : 'asc') . '">Age</a></th></tr>';
foreach ($data as $row) {
    echo '<tr><td>' . $row['id'] . '</td><td>' . $row['name'] . '</td><td>' . $row['age'] . '</td></tr>';
}
echo '</table>';
?>