70

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 protected] ) 

$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

4
  • 9
    Your definition of the $user_meta array is not valid for a PHP array, it's print_r() output, formatted for human readability Commented Aug 1, 2013 at 14:25
  • 1
    P.S. inline anonymous functions only work in PHP 5.3+ Commented Aug 1, 2013 at 14:39
  • @Paulpro why did you rollback the format change? Commented Sep 2, 2016 at 6:09
  • problem in in the email! need to put that in quotes "[email protected]" Commented Jul 12, 2018 at 17:49

4 Answers 4

118

I hope this will help:

$user_meta = array_map(function ($a) { return $a[0]; }, $user_meta);
Sign up to request clarification or add additional context in comments.

4 Comments

This is a good answer, except the remark there must be a space between the keyword function and its parameters. Because i removed the space and got no problem.
The space after function keyword really doesn't matter...!
The space changes nothing.
Yes, the syntax seems fine. There error should be from $user_meta definition.
19

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.

7 Comments

I am getting same error when I pass the array with arguments..I could only make it work by calling function explicitly.. here
Which version of PHP do you have? Most people have at least 5.3 now, and you're code worked fine in 5.3 and up.
I am using php 5.5 only you can check the updated link..again it is showing errors
@BLPraveen There are no errors in the section titled: Output for 5.3.0 - 5.5.1. Only in the older version sections.
@BLPraveen Added some output so you can see that's it's working: 3v4l.org/5NgCc
|
11

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

1 Comment

fn syntax style is available from PHP 7.4.0 www.php.net/manual/en/function.array-map.php#example-5041
3

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.