3

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.

1
  • why you need this redundant data ? Commented Jun 28, 2018 at 8:10

3 Answers 3

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

it's getting the user_id value as blank but in above it's 5
1

Add a simple use statement:

$keywords = array_map(function($arr) use ($user_id) {
    return $arr + ['user_id' => $user_id];
}, $keywords);

Comments

0

Modify rows by reference and pass in the user_id value as the third parameter of array_walk(). (Demo)

array_walk($keywords, fn(&$v, $k, $u) => $v = ['user_id' => $u] + $v, $user_id);

Or with arrow functions, you can pass the user_id value without relying on use(). (Demo)

var_export(
    array_map(fn($v) => ['user_id' => $user_id] + $v, $keywords)
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.