1

I'm not an expert of Collections concept in CakePhp 4, and I don't know how to pass a variable in Collection::map()

$item = [
        'attributes' => [
            'class' => 'mon-li-{{id}}',
            'data-truc' => 'li-{{id}}'
        ],
        'linkAttrs' => ['class' => 'mon-lien', 'style' => 'text-transform: uppercase']
    ];

    $id = 5;
    
    $item = collection($item)
                    ->map(function ($value, $key){
                        return preg_replace('/{{id}}/', $id, $value); // $id is undefined

                    })
                    ->toArray();

It gives : Notice (8): Undefined variable: id

How can I do for my function to be able to know $id ?

Oliv
  • 236
  • 3
  • 12

1 Answers1

0

The use keyword helps with this:

$item = collection($item)
      ->map(function ($value, $key) use ($id) { // <-- See `use`
          return preg_replace('/{{id}}/', $id, $value);
      })
      ->toArray();

PHP Manual: Anonymous Functions

Geoffrey
  • 5,407
  • 10
  • 43
  • 78