How can PHP code be optimized for efficient sorting of tables based on different criteria?

To optimize PHP code for efficient sorting of tables based on different criteria, you can use the usort() function along with a custom comparison function. This allows you to define specific sorting logic based on different criteria, improving the performance of the sorting process.

// Sample array of data to be sorted
$data = [
    ['name' => 'Alice', 'age' => 25],
    ['name' => 'Bob', 'age' => 30],
    ['name' => 'Charlie', 'age' => 20]
];

// Custom comparison function for sorting by age
function sortByAge($a, $b) {
    return $a['age'] - $b['age'];
}

// Sort the data array by age using the custom comparison function
usort($data, 'sortByAge');

// Output sorted data
foreach ($data as $item) {
    echo $item['name'] . ' - ' . $item['age'] . PHP_EOL;
}