Ambrosius Topor

Notiz — 2017-08-20

Pluck in PHP

We can implement a pluck function in PHP:

function pluckItem($property) {
    return function($item) use ($property) {
        return $item[$property];
    };
}
function pluck($array, $property) {
    $pluckItem = function($item) use ($property) {
        return $item[$property];
    };
    return array_map($pluckItem, $array);
}

Taken some example data (a list of users with name and age properties):

$persons = array(
    array(
        'name' => 'John',
        'age' => 23
    ),
    array(
        'name' => 'Bob',
        'age' => 35
    ),
    array(
        'name' => 'Steve',
        'age' => 54
    )
);

We can easily extract the names and by performing additional calculations get the summed up age:

$names = array_map(pluckItem('name'), $persons);
$ages = array_map(pluckItem('age'), $persons);
$ages_total = array_sum($ages);

print_r($names);
print_r($ages_total);
$names = pluck($persons, 'name');
$ages = pluck($persons, 'age');
$ages_total = array_sum($ages);

print_r($names);
print_r($ages_total);

Comments

There are no comments yet.

Thanks for your contribution!
Your comment will be visible once it has been approved.

An error occured—please try again.

Add Comment