-
-
Save osazeblogger/e3d3df101a976a1dab91ed404af5c460 to your computer and use it in GitHub Desktop.
PHP Array pluck function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' | |
); | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment