How can PHP developers efficiently calculate averages for specific elements in an array?

When calculating averages for specific elements in an array, PHP developers can efficiently achieve this by using built-in array functions such as array_filter and array_sum. By filtering the array to only include the specific elements needed for the average calculation, developers can then sum these elements and divide by the count to get the average.

// Sample array with values
$array = [10, 20, 30, 40, 50];

// Filter the array to only include specific elements (e.g., elements at index 1 and 3)
$filteredArray = array_filter($array, function($key) {
    return $key == 1 || $key == 3;
}, ARRAY_FILTER_USE_KEY);

// Calculate the average of the filtered elements
$average = array_sum($filteredArray) / count($filteredArray);

echo "Average: " . $average; // Output: Average: 30