Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to access a variable inside array map function

Tags:

arrays

scope

php

I want to add a key in the multidimensional array using the array_map() function.

$keywords = [['keyword'=>'designing'],['keyword'=>'logo designing']];
$user_id = 5;
$keywords = array_map(function($arr){
    return $arr + ['user_id' => $user_id];
}, $keywords);

I want the output as

$keywords = [['user_id'=>5,'keyword'=>'designing'],['user_id'=>5,'keyword'=>'logo designing']];

but it's showing undefined variable $user_id.

like image 475
Arun Sharma Avatar asked Jun 30 '26 16:06

Arun Sharma


1 Answers

The variable $user_id is not known in the anonymous function passed as the first argument to array_map().

You can easily solve this by using the use keyword that lets the function inherit the $user_id variable defined in the parent context.

$keywords = [['keyword'=>'designing'],['keyword'=>'logo designing']];
$user_id = 5;

$keywords = array_map(function($arr) use ($user_id) {
    return $arr + ['user_id' => $user_id];
}, $keywords);
like image 80
axiac Avatar answered Jul 03 '26 06:07

axiac