Skip to content

Instantly share code, notes, and snippets.

@ozh
Forked from sobi3ch/gist:5451004
Last active July 26, 2022 11:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ozh/82a17c2be636a2b1c58b49f271954071 to your computer and use it in GitHub Desktop.
Save ozh/82a17c2be636a2b1c58b49f271954071 to your computer and use it in GitHub Desktop.
PHP Array pluck function
<?php
$foods = array(
array(
'id' => 4,
'name' => 'Banana',
'color' => 'Yellow',
),
array(
'id' => '5',
'name' => 'Apple',
'color' => 'Red',
),
array(
'id' => 2,
'name' => 'Lettuce',
'color' => 'Green',
),
array(
'id' => '7',
'name' => 'Apple',
'color' => 'Red',
),
);
$food_names = array_pluck( $foods, 'name' );
/*
array(
'Banana',
'Apple',
'Lettuce',
'Apple'
);
*/
<?php
/**
* Pluck an array of values from an array. (Only for PHP 5.3+)
*
* @param $array - data
* @param $key - value you want to pluck from array
*
* @return plucked array only with key data
*/
function array_pluck($array, $key) {
return array_map(function($v) use ($key) {
return is_object($v) ? $v->$key : $v[$key];
}, $array);
}
@0m3r
Copy link

0m3r commented Aug 31, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment