PHP

Calculate Basic Statistics for Numeric PHP Arrays

Quickly compute the sum, average, minimum, and maximum values from a numeric PHP array using built-in functions for data analysis.

<?php
$numbers = [10, 25, 5, 30, 15, 20];

$sum = array_sum($numbers);
// $sum will be 105

$count = count($numbers);
$average = ($count > 0) ? ($sum / $count) : 0;
// $average will be 17.5

$min = min($numbers);
// $min will be 5

$max = max($numbers);
// $max will be 30

// You can also use array_reduce for custom statistics, e.g., product
$product = array_reduce($numbers, function($carry, $item) {
    return $carry * $item;
}, 1);
// $product will be 112500000
?>
How it works: PHP provides dedicated functions for common statistical operations on numeric arrays. `array_sum()` quickly calculates the total sum. `count()` gets the number of elements. `min()` and `max()` find the smallest and largest values respectively. The example also demonstrates `array_reduce()` for more complex aggregations like calculating the product of all elements, offering great flexibility for custom statistics.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs