Skip to content

Saner array_(sum|product)() #10161

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Mar 7, 2023
Merged

Saner array_(sum|product)() #10161

merged 15 commits into from
Mar 7, 2023

Conversation

Girgias
Copy link
Member

@Girgias Girgias commented Dec 23, 2022

RFC: https://wiki.php.net/rfc/saner-array-sum-product

The current behaviour of array_sum() and array_product() is outright insane.

  • It ignores entries that are arrays or objects without any warning
  • It casts the remaining values to int|float to perform the operation, this includes resources and non-numeric strings which as of PHP 8.0 throw TypeErrors when used with arithmetic operations.

The objective of this PR, and yet to be written RFC, is to align the behaviour of these two functions as close as possible to doing: array_reduce($input, fn($carry, $value) => $carry + $value, 0) for array_sum($input) and array_reduce($input, fn($carry, $value) => $carry * $value, 1) for array_product($input).

To achieve this in a backwards compatible manner, we emit warnings for types which should throw type errors while still applying the current behaviour. Moreover, we now support performing the binary operation on objects that support it instead of ignoring them.

The one difference with the array_reduce() implementation is that if the traversal of the array encountered objects that supported the relevant binary operation, it also needs to be castable to int|float to preserve the return type of these functions.

@Girgias Girgias merged commit 3b06618 into php:master Mar 7, 2023
@Girgias Girgias deleted the sane-array-ops branch March 7, 2023 15:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants