OneBite.Dev - Coding blog in a bite size

Find The Average Of All Elements In An Array In PHP

Code snippet for how to Find The Average Of All Elements In An Array In PHP with sample and detail explanation

Dealing with array data is one of the most common tasks for PHP developers. In this article, we will guide you through finding the average of all elements in an array using PHP.

Code snippet for finding the average of an array using PHP

Below is a simple PHP code to find the average of all elements within an array.

<?php
$array = array(1, 2, 3, 4, 5, 6);
$average = array_sum($array) / count($array);
echo $average;
?>

Code Explanation for finding the average of an array using PHP

Let’s break down the PHP script into simple steps for better understanding.

  1. Defining the array: We first start by defining an array for which we want to find the average. In this case, it’s an array holding the numbers 1 through 6.
$array = array(1, 2, 3, 4, 5, 6);
  1. Calculating the sum and counting the elements of the array: Next, we use the array_sum() function provided by PHP which sums up all the values in the array. We also need to find out the number of elements in the array using the count() function.
$array_sum = array_sum($array);
$array_count = count($array);
  1. Calculating the Average: After obtaining the sum of the array and the number of elements, we can now calculate the average by dividing the sum by the count.
$average = $array_sum / $array_count;
  1. Printing the Result: Finally, we output the result using the echo statement, which will display the average of all elements in the array.
echo $average;

That’s it! You have successfully calculated the average of all elements within an array using PHP. By using built-in PHP functions like array_sum and count, you can quickly and efficiently find out the average of any given array.

php