Home > Net >  How to pass variable to $callback Collection::map($callback) in CakePHP 4.2?
How to pass variable to $callback Collection::map($callback) in CakePHP 4.2?

Time:09-27

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 ?

CodePudding user response:

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

  • Related