PHP array mapping

Is there a cleaner way than foreach to get an array of all label values?

 $methods[0]['label'] = 'test'; $methods[0]['nr'] = 99; $methods[1]['label'] = 'whatever'; $methods[1]['nr'] = 10; foreach($methods as $method) { $methodsLabel[] = $method['label']; } 
+12
source share
6 answers

No, there is no faster way than your implemented code. All other methods will be slower due to the overhead of calling the function. For a small array, the difference will be trivial, but for a large (100 members or so, depending on implementation) the difference can be huge ...

You could array_map it, but I would stick with the raw PHP that you posted above ... It is easier to maintain and IMHO more readable ...

In the end, tell me which, at first glance, it says that it does more:

 $results = array(); foreach ($array as $value) { $results[] = $value['title']; } 

vs

 $results = array_map(function($element) { return $element['title']; }, $array ); 

Or:

 $callback = function($element) { return $element['title']; } $results = array_map($callback, $array); 

Personally, the first one makes it the best for me. This immediately becomes apparent, not knowing anything that he does. Others require knowledge of the semantics of array_map to understand. A couple that with the fact that array_map slower, and this is a double win for foreach .

The code should only be as elegant as necessary. It should be readable, first of all ...

+23
source

Of course use array_map :

 function getLabelFromMethod($method) { return $method['label']; } $labels = array_map('getLabelFromMethod', $methods); 

If you are using PHP 5.3+, you can also use the lambda function:

 $labels = array_map(function($m) { return $m['label']; }, $methods); 
+15
source
 array_map('array_shift', $methods); 

Here it is assumed that the label will be the first element of each array.

+5
source

In PHP 5.3+, you can use an anonymous function paired with array_map.

 $methodsLabel = array_map(function($item) { return $item['label']; }, $methods); 
+4
source

Starting with PHP 5. 5+, this is exactly what array_column does:

 $methodsLabel = array_column($methods, 'label'); 

http://php.net/manual/function.array-column.php


3v4l example: https://3v4l.org/ZabAb

+4
source

If the label is the first element in the array, then "current" with array_map will work fine.

 array_map('current', $methods); 
+2
source

All Articles