Create a PHP script that calculates the average of an array of numbers.

<?php
function calculateAverage($numbers) {
    if (empty($numbers)) {
        return null;
    }

    $sum = array_sum($numbers);
    $count = count($numbers);
    
    return $sum / $count;
}

$numberArray = [5, 12, 8, 3, 10];
$average = calculateAverage($numberArray);

echo "The average of the numbers is: $average";
?>
  • The script defines a function calculateAverage that takes an array of numbers as input and returns the average.
  • If the array is empty, the function returns null.
  • It uses array_sum to calculate the sum of the numbers and count to get the number of elements.
  • The average is calculated by dividing the sum by the count.
  • The script then calls the function with a sample array ($numberArray) and prints the result.

Post your Answer