What are the best practices for calculating the average of values within specific ranges in a multidimensional array in PHP?

When calculating the average of values within specific ranges in a multidimensional array in PHP, it is important to iterate through the array and filter out the values that fall within the specified ranges. Once the values are filtered, calculate the average of the remaining values within each range.

function calculateAverageInRange($array, $startRange, $endRange) {
    $total = 0;
    $count = 0;

    foreach ($array as $subArray) {
        foreach ($subArray as $value) {
            if ($value >= $startRange && $value <= $endRange) {
                $total += $value;
                $count++;
            }
        }
    }

    if ($count > 0) {
        return $total / $count;
    } else {
        return 0;
    }
}

// Example usage
$multiArray = [
    [10, 20, 30],
    [15, 25, 35],
    [5, 15, 25]
];

$startRange = 10;
$endRange = 20;

$averageInRange = calculateAverageInRange($multiArray, $startRange, $endRange);
echo "Average of values between $startRange and $endRange: $averageInRange";