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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With