getButterfly Logo getButterfly code wrangling since 2005


So, you pushed all your values to an array, and now you need to calculate the average value. Even if you have thousands of values, this function will iterate through all array itemsĀ and return the average value:

function get_average($numbers, $decimals) {
    $a = $numbers;
    $b = 0;
    $c = 0;
    $d = 0;
    foreach($a as $b) {
        $c = $c + $b;

    return number_format($c/$d, $decimals);

This is how you display the average value:

$myarray = array();
// push elements to array
echo get_average($myarray, 2);

The function works both with integer values and with float values. Make sure you actually declare the variable as an array before pushing items into it. Some PHP versions might complain about this. Use var_dump($myarray) or print_r($myarray) to check if your array is well-formed.

As a bonus, this is how I use print_r():

function array_dump($array) {
    echo '<pre>';
    echo '</pre>';


Image credit

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a reply