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'];
}
Definition and Usage. The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function.
The map class in PHP is a collection of key-value pairs. The structure of a map is similar to an array in terms of the sequence, performance, and memory efficiency. The map() function is used to apply a callback function on each value within the map.
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.
The resulting array of array_map has the same length as that of the largest input array; array_walk does not return an array but at the same time it cannot alter the number of elements of original array; array_filter picks only a subset of the elements of the array according to a filtering function.
No, there is no faster way than your implemented code. All other methods will be slower due to the overhead of a function call. For a small array the difference will be trivial, but for a large one (100 members or so, depending on implementation), the difference can be huge...
You could array_map
it, but I'd stick with the raw PHP you posted above... It's easier to maintain and IMHO more readable...
After all, tell me which at a glance tells you what 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 does it for me the best. It's immediately obvious without knowing anything what it's doing. The others require knowledge of array_map
semantics to understand. Couple that with the fact that array_map
is slower, and it's a double win for foreach
.
Code should only be as elegant as necessary. It should be readable above all else...
Sure, use array_map
:
function getLabelFromMethod($method) {
return $method['label'];
}
$labels = array_map('getLabelFromMethod', $methods);
If you are on PHP 5.3+, you can also use a lambda function:
$labels = array_map(function($m) {
return $m['label'];
}, $methods);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With