Chalarangelo / 30-seconds-of-php

Short PHP code snippets for all your development needs

Home Page:https://www.30secondsofcode.org/php/p/1

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Not 100% safe average example

matiit opened this issue · comments

Despite "realiness" of following example I think it'd be good if it would be mistake proof, especially when it's something for others to learn from.

php > echo average(1,3,4,5);

3.25

php > echo average();

 

Warning: Division by zero in php shell code on line 3

NAN

php >

Quick "solution" might be

function average(...$items)
{
    return count($items) === 0 ? 0 :
     array_sum($items) / count($items);
}

You're welcome make a PR.
Just update on snippets/average.md & src/helpers.php

Can be closed now, thanks.

commented

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for any follow-up tasks.