What are alternative methods to switch case statements for dynamic sorting in PHP?

When dealing with dynamic sorting in PHP, using switch case statements can become cumbersome and repetitive, especially if there are many sorting options. An alternative method is to use an associative array where the keys represent the sorting options and the values are callback functions that perform the sorting. This approach allows for a more concise and flexible way to handle dynamic sorting.

// Define an associative array with sorting options and corresponding callback functions
$sortingOptions = [
    'name' => function($a, $b) {
        return strcmp($a['name'], $b['name']);
    },
    'age' => function($a, $b) {
        return $a['age'] - $b['age'];
    },
    // Add more sorting options as needed
];

// Sort the data based on the selected sorting option
$selectedOption = 'name'; // Can be dynamically set based on user input
usort($data, $sortingOptions[$selectedOption]);