[php-src] Issue #8183: New functions array_avg and array_median

From: Date: Wed, 09 Mar 2022 13:38:01 +0000
Subject: [php-src] Issue #8183: New functions array_avg and array_median
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-240275@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/8183 Author: niconoe- ### Description Hi ! Maybe this has been already requested but I can't find it on GitHub. If this issue is a duplicate, please close it. In order to avoid user implementations of the calculations of averages and medians from an array of floats, I'm proposing the addition of 2 new PHP internal functions in the "array functions list": * array_avg(array<float> $array): float * array_median(array<float> $array): float Those functions would act just like array_sum and array_product, but to respectively calculate the arithmetical average and the median of a numeric list. Such functions already exist in some other languages, and I think it could be helpful for PHP developers too. As the average and median calculation is implying a division by the number of elements in the list, and such number could be 0, in order to be errorless and not mixing return types, my proposal would be to return 0 if $array is empty for each of those functions. Here are some possible polyfills: ```php function array_avg(array $array): float { return [] === $array ? 0 : array_sum($array) / count($array); } function array_median(array $array): float { $nbElements = count($array); if (0 === $nbElements) { return 0; } if ($nbElements % 2) { return $array[floor($nbElements / 2)]; } return ($array[$nbElements / 2 - 1] + $array[$nbElements / 2]) / 2; } ``` Those mathematical functions are often use even if not working on the statistical domain, and could be easily added into the PHP ecosystem IMO. Only BCBreak possible is when there are already user-defined functions called "array_avg" or "array_median". * [array_avg search on GitHub](https://github.com/search?l=PHP&q=%22array_avg%22&type=code) * [array_median search on GitHub](https://github.com/search?l=PHP&q=%22array_median%22&type=Code) What do you think about? Thanks a lot! Best regards

« previous php.bugs (#240275) next »