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";
Related Questions
- What are the implications of using longint vs. int for IDs in PHP?
- How can PHP be utilized to group and display data from a MySQL table based on a specific category efficiently?
- How can PHP developers efficiently handle situations where values in an array need to be grouped into ranges, as seen in the example provided?