What are some best practices for using arrays in PHP to handle frequency sorting tasks like this?
When handling frequency sorting tasks in PHP using arrays, a common approach is to iterate through the input data and store the frequencies of each element in an associative array. Then, sort the array based on the frequencies in descending order to get the elements sorted by their occurrence frequency. Finally, iterate through the sorted array to output the elements in the desired order.
// Input data
$data = [2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12];
// Count the frequency of each element
$freq = array_count_values($data);
// Sort the array based on frequencies in descending order
arsort($freq);
// Output the elements sorted by frequency
foreach ($freq as $element => $count) {
echo "$element appears $count times" . PHP_EOL;
}