How can PHP variables be used to make sorting data more flexible and efficient?

Using PHP variables to store sorting criteria allows for more flexibility and efficiency when sorting data. By storing the sorting criteria in a variable, you can easily change the sorting order or criteria without modifying the sorting function itself. This makes the code more maintainable and adaptable to different sorting requirements.

// Define the sorting criteria in a variable
$sortCriteria = 'name';

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

// Custom sorting function using the variable
usort($data, function($a, $b) use ($sortCriteria) {
    return $a[$sortCriteria] <=> $b[$sortCriteria];
});

// Output sorted data
print_r($data);