array_map inline anonymous function

PhpArray Map

Php Problem Overview


I tested inline anonymous function with array_map here

and it worked but when I tried same with $user_meta it is not working.

$user_meta = Array ( [interest] => Array ( [0] => Array ) [type] => 
     Array ( [0] => Array ) [user_status] => Array ( [0] => deny)
     [firstname] => Array ( [0] => ) [lastname] => Array ( [0] => B ) 
     [email] => email@cc.com ) 

$user_meta = array_map(function($a) { return $a[0]; },$user_meta);

> "Parse error: syntax error, unexpected T_FUNCTION, expecting ')' in"

here is the test link showing error

Php Solutions


Solution 1 - Php

I hope this will help:

$user_meta = array_map(function ($a) { return $a[0]; }, $user_meta);

Solution 2 - Php

There's nothing wrong with the array_map line, but everything before it is wrong. That is the output of a print_r not PHP code. Compare how you define the array in the two links you posted.

Solution 3 - Php

That's not an answer to your question, but since you want to return the first key of each sub-array, you can just use array_column.

$user_meta = array_column($user_meta, 0);

Solution 4 - Php

Slightly shorter could be

$user_meta = array_map(fn ($a) => $a[0], $user_meta);

But I would prefer the array_column approach for such an array_map

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionB L PraveenView Question on Stackoverflow
Solution 1 - PhpDat TTView Answer on Stackoverflow
Solution 2 - PhpPaulView Answer on Stackoverflow
Solution 3 - PhpHichem BenaliView Answer on Stackoverflow
Solution 4 - PhpIgbanamView Answer on Stackoverflow