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@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

Pritamkumar
  • 682
  • 1
  • 11
  • 30
B L Praveen
  • 1,812
  • 4
  • 35
  • 60

4 Answers4

106

I hope this will help:

$user_meta = array_map(function ($a) { return $a[0]; }, $user_meta);
Dat TT
  • 2,850
  • 2
  • 16
  • 18
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.

Paul
  • 139,544
  • 27
  • 275
  • 264
  • I am getting same error when I pass the array with arguments..I could only make it work by calling function explicitly.. [here](http://3v4l.org/F0Sac) – B L Praveen Aug 02 '13 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 02 '13 at 13:14
  • I am using php 5.5 only you can check the updated link..again it is showing errors – B L Praveen Aug 02 '13 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 02 '13 at 15:10
  • @BLPraveen Added some output so you can see that's it's working: http://3v4l.org/5NgCc – Paul Aug 02 '13 at 15:11
  • The array syntax is fine... `array('0' => '')` is just going to define an associative array with a key '0' pointing to an empty string. The error's almost certainly just that he's on a PHP version older than 5.3. – George Sep 02 '16 at 05:44
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

Igbanam
  • 5,904
  • 5
  • 44
  • 68
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);
Hichem Benali
  • 413
  • 3
  • 6