Gridview: Inner function: Put value into external array

Hi again :wink:

The following gridColumn array is used for a gridview widget:

                            $propertyId = [];

                            $gridColumn = [
                                    'attribute' => 'serial',
                                    'label' => '#',
                                    'format' => 'raw',
                                    'value' => function ($m, $k, $i) use ($propertyId) {
                                        if (!array_key_exists($m->id, $propertyId)) {
                                            $id = $i + 1;
                                            $key = $m->id;                                            
                                            $propertyId[$key] = &$id;
                                        } else {
                                            $id = $propertyId[$m->id];
                                        $r = '<div class="markerNumber" style="cursor: pointer;" data-id="' . $m['id'] . '">'
                                                . '<span class="badge badge-pill badge-primary">'
                                                . $id
                                                . '</span>'
                                                . '</div>';

                                        return $r;

The last print_r show single arrays

Array ( [9] => 1 ) Array ( [10] => 2 ) Array ( [10] => 3 ) Array ( [10] => 4 ) Array ( [10] => 5 )

the fist, nothing. I suggest the elements will be insert by reference due to the fact that after the inner function is finished, the array element is forgotten.

How can avoid that the array elements are missing?

Thanks and best regards,

Iโ€™ve tried different things without success, why donโ€™t save php the value to the external array permanently? :frowning:

Different contexts. Use the grid property of the column to reach the external array.
(not tried)

@strtob have you tried passing the variable by reference?
Because you create a closure each new row, the variable is a copy of the empty array.

See this question and answers on Stackoverflow: closures - Modifying a variable passed to a PHP anonymous function doesn't appear to be reflected in variables original scope - Stack Overflow

This may clear things up a bit
source for getDataCellValue

(This is from DataColumn.php so this this will point to the column object)
(not verified)

Edit: Ignore my answer if propertyId is global and not declared in the grid.

Thanks a lot for your time to answer me and help me to solve my problem!!!

the solution is to use & in the function declaration before the external variable

'format' => 'raw',
                                        'value' => function ($m, $k, $i) use (&$propertyId) {


This save my year! :wink:

All the best,