Useful PHP helpers: array_pick

A long time ago I added this helper to CCF's CCArr class. If you are doing a lot of Database operation you will come often to the point where you have to get a value from every row. Obviously it's not hard to write a loop doing that, but this way you will repeat yourself. This mini helper makes you write a little less code. Which is good!

Usage

Of course the implementation into your framework or application is your turn.

$people = [
    [ 'name' => 'John', 'age' => 33 ],
    [ 'name' => 'Johanna', 'age' => 21 ],
];

Now we can pick for example all names:

// returns [ 'John', 'Johanna' ]
$names = array_pick( $people, 'name' );

The function

/**
 * Pick a value from every array inside of an array collection
 * 
 * @param array[array]          $arrayCollection
 * @param string                $pickKey
 * @return array
 */
function array_pick(array $arrayCollection, $pickKey)  
{
    $pickedValues = array();

    foreach ($arrayCollection as $array) {
        if (is_array($array) && isset($array[$pickKey])) {
            $pickedValues[] = $array[$pickKey];
        }
    }

    return $pickedValues;
}
Mario Döring

Mario Döring

http://clancats.ch

Software Engineer, ClanCats Dude, cineman.ch Developer and general Idiot.

View Comments
Navigation