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

cesarfp's avatar

Why my PHP array is null

My code is the following;

$dirtyElements = array();

    $collection = $items->each(function ($item, $key) use ($dirtyElements) {
        if($item->isDirty()) {
            
            $dirtyElements[] = $item->getDirty();
            //dd($dirtyElements);
        }
    });

dd($dirtyElements)

Outside each method $dirtyElement is null. Why?

0 likes
3 replies
Tray2's avatar

It's all about scope in this case.

Because you have two $dirtyElements on that is global in your method and one that is in your closure.

$dirtyElements = array(); //The global one

    $collection = $items->each(function ($item, $key) use ($dirtyElements) {
        if($item->isDirty()) {
            
            $dirtyElements[] = $item->getDirty(); // The local one in the closure.
            //dd($dirtyElements); //The local one.
        }
    });

dd($dirtyElements) //The global one

I suggest you read this http://php.net/manual/en/functions.anonymous.php

1 like
Snapey's avatar
Snapey
Best Answer
Level 122

You can pass $dirtyElements in by reference by prefixing with &

however, you would be better using collections to filter to just those items that are dirty and then call getdirty on those

something like

$dirtyElements = $items->filter(function ($item) {
        return $item->isDirty();
    })
    ->each($function($item) {
        return $item->getDirty();
    });

cesarfp's avatar

@Tray2 your answer and your reference were very helpful. Thanks.

@Snapey your example looked like nice and clean but I'm afraid each method does not work like that. I mean, I wanted dirty array but in that way it only returned me the whole model again. But your answer helped me to resolve my problem. Thanks.

Please or to participate in this conversation.