64

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

4 Answers 4

107

I hope this will help:

$user_meta = array_map(function ($a) { return $a[0]; }, $user_meta);
4
  • 3
    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. Feb 21, 2018 at 5:01
  • 7
    The space after function keyword really doesn't matter...! Jun 28, 2018 at 11:03
  • 2
    The space changes nothing.
    – drew7721
    Jul 12, 2018 at 17:50
  • 1
    Yes, the syntax seems fine. There error should be from $user_meta definition.
    – Dat TT
    Jul 13, 2018 at 2:19
18

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.

6
  • I am getting same error when I pass the array with arguments..I could only make it work by calling function explicitly.. here Aug 2, 2013 at 10:43
  • 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.
    – Paul
    Aug 2, 2013 at 13:14
  • I am using php 5.5 only you can check the updated link..again it is showing errors Aug 2, 2013 at 13:55
  • @BLPraveen There are no errors in the section titled: Output for 5.3.0 - 5.5.1. Only in the older version sections.
    – Paul
    Aug 2, 2013 at 15:10
  • @BLPraveen Added some output so you can see that's it's working: 3v4l.org/5NgCc
    – Paul
    Aug 2, 2013 at 15:11
8

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.