Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_map inline anonymous function

Tags:

php

array-map

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

like image 343
B L Praveen Avatar asked Aug 01 '13 14:08

B L Praveen


People also ask

What is the use of array_map in PHP?

The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.

Does array map preserve keys?

The returned array will preserve the keys of the array argument if and only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys.

How to create array map PHP?

To create a new array from an existing PHP array, you can use the array_map(functionName, array1, array2, ...) function. The array_map() function iterates over all the elements of an array and returns a new array containing the results of applying the given callback function to the array elements.

Is there a map function in PHP?

The Ds\Map::map() function of the Map class in PHP is used to apply a callback function to a Map object. This returns the result of applying the callback function to each value present on the map.


3 Answers

I hope this will help:

$user_meta = array_map(function ($a) { return $a[0]; }, $user_meta);
like image 89
Dat TT Avatar answered Oct 23 '22 17:10

Dat TT


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.

like image 37
Paul Avatar answered Oct 23 '22 17:10

Paul


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

like image 6
Igbanam Avatar answered Oct 23 '22 16:10

Igbanam