Blog
Pilot logbook
Bucket list
Guestbook

PHP program to compute standard deviation

Tags
Meta
1 minutes read -

Find standard deviation of array of inputs in PHP.

function standard_deviation(array $input): float
{
    // sanitize empty array elements and non numerics but allow zero values
    $input = array_filter($input, static function ($v) {
        return ! in_array($v, [false, null, ''], true) && is_numeric($v);
    });

    $count = count($input);

    $result = 0.0;

    if ($count === 0) {
        // throw exception OR return $result if you want to return zero
        throw new RuntimeException('Cannot compute standard deviation without input');
    }

    $avg = array_sum($input) / $count;

    foreach ($input as $i) {
        $result += ($i - $avg) ** 2;
    }

    return number_format(sqrt($result / $count), 4); // increase '4' value for more precision if needed
}

PHP Unit tests

/**
 * @test
 */
public function standard_deviation_computes_correctly(): void
{
    $scenarios = [
        [
            'expectation' => 1.3437,
            'input' => [
                -1, 0, '0', 1, '2', 3, '',
            ],
        ],
        [ // test with non numerics
            'expectation' => 1.8548,
            'input' => [
                'xyz', '-1', '0', 3.14159, '3.14159'
            ],
        ],
    ];

    foreach ($scenarios as $scenario) {
        self::assertSame(
            $scenario['expectation'],
            standard_deviation($scenario['input'])
        );
    }
}