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!


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

Solution Architect creating the black magic for Cineman, handyman for ClanCats, useless PHP things Entrepreneur and general Idiot.

View Comments