Skip to content

Added "key" parameter to array_reduce callback #14986

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

Bilge
Copy link

@Bilge Bilge commented Jul 16, 2024

This changes the signature of the array_reduce callback from:

callback(mixed $carry, mixed $item): mixed

to:

callback(mixed $carry, mixed $item, int|string $key): mixed
@Bilge Bilge force-pushed the array-reduce-key branch from fd54a96 to 6a47510 Compare July 16, 2024 23:06
@divinity76
Copy link
Contributor

divinity76 commented Jul 17, 2024

guess it's worth mentioning that it can easily be built in userland?

function array_reduce_with_key(array $array, callable $callback, mixed $initial = null): mixed
{
    $result = $initial;
    foreach ($array as $key => $value) {
        $result = $callback($result, $value, $key);
    }
    return $result;
}
@Bilge
Copy link
Author

Bilge commented Jul 17, 2024

I don't think that's worth mentioning, unless you can justify why it precludes the usefulness of having it in core?

@divinity76
Copy link
Contributor

divinity76 commented Jul 17, 2024

well there is a backwards-compatibility concern, for example

$array = [[1, 2], [3, 4], [5, 6]];
$flattened_array = array_reduce($array, array_merge(...), []);

today generates

array(1,2,3,4,5,6)

but in your branch presumably generates

Fatal error: Uncaught TypeError: array_merge(): Argument #3 must be of type array, int given

it might not be worth the BC break to do it in core (i don't know)

edit: would not affect the vast majority of code in the wild (as you said in the ML, most functions don't care about an extra argument.. but exceptions exist)

@nielsdos
Copy link
Member

This would indeed require an RFC because there's a BC concern, even though the BC impact is likely limited.

@divinity76
Copy link
Contributor

the bc problem could be resolved by adding a 4th argument bool $callback_with_key = false to array_reduce

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment