powtac
powtac

Reputation: 41040

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'];
}

Upvotes: 18

Views: 42604

Answers (7)

Gary Thomas
Gary Thomas

Reputation: 2331

Arrow functions have been introduced into PHP 7.4, which makes this a little bit cleaner.

$methodsLabel = array_map(fn($x) => $x['label'], $methods)

Upvotes: 3

autonymous
autonymous

Reputation: 303

As of 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

Upvotes: 10

Ravi Hirani
Ravi Hirani

Reputation: 6539

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

array_map('current', $methods); 

Upvotes: 3

ircmaxell
ircmaxell

Reputation: 165191

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

Upvotes: 29

Gaurav
Gaurav

Reputation: 28755

array_map('array_shift', $methods);

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

Upvotes: 6

efritz
efritz

Reputation: 5203

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

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

Upvotes: 5

Jacob Relkin
Jacob Relkin

Reputation: 163228

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

Upvotes: 18

Related Questions