Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rawilk's avatar
Level 47

PHP 7.4 arrow function variable reference

In a function I have, I'm trying to iterate over a collection of ids and through each iteration, add the result of a method call for that id. However, nothing I've tried seems to work, but I can get it to work with a normal closure.

private function getFormData(Collection $requests): array
{
    $assetDeploymentTypes = [];

    $requests->pluck('family.school_id')
        ->unique()
        // ->each(function ($id) use (&$assetDeploymentTypes) {
                // This works since I can pass the variable in by reference
        //     $assetDeploymentTypes[$id] = app(AssetDeploymentTypeRepository::class)->deployableTypes($id, ['id', 'name']));
        // });
        // This doesn't because I can't find a way to pass it by reference
        ->each(fn ($id) => $assetDeploymentTypes[$id] = app(AssetDeploymentTypeRepository::class)->deployableTypes($id, ['id', 'name']));

    dd($assetDeploymentTypes); // Shows empty array
}

Maybe I'm just misunderstanding the uses of arrow functions, but it would be nice to write it this way. I've also tried writing it like (fn& ($id) => ...) like seen here: https://stitcher.io/blog/short-closures-in-php, but then I get the error of "Only variable references should be returned by reference".

0 likes
5 replies
tykus's avatar

Why not map; it would mean there is no need for the temporary variable (and no reference to pass!):

private function getFormData(Collection $requests): array
{
    $assetDeploymentTypes = $requests->pluck('family.school_id')
        ->unique()
        ->map(fn ($id) => app(AssetDeploymentTypeRepository::class)->deployableTypes($id, ['id', 'name']));
}
rawilk's avatar
Level 47

@tykus I like that solution, however the only drawback of that is I lose having that school id as the key for each element.

tykus's avatar
tykus
Best Answer
Level 104

So mapWithKeys rather than map

private function getFormData(Collection $requests): array
{
    $assetDeploymentTypes = $requests->pluck('family.school_id')
        ->unique()
        ->mapWithKeys(fn ($id) => [$id => app(AssetDeploymentTypeRepository::class)->deployableTypes($id, ['id', 'name'])]);
}
rawilk's avatar
Level 47

mapWithKeys didn't exactly work the way I expected it to, but I think that was because I just had a collection of ids. Combining ->keyBy(fn ($id) => $id) and map, I was able to get it to work correctly though.

rawilk's avatar
Level 47

I also didn't try it like you have as I didn't see that until now.

Please or to participate in this conversation.