Last active
October 24, 2017 17:10
-
-
Save sobi3ch/5451004 to your computer and use it in GitHub Desktop.
PHP Array pluck function
This file contains hidden or 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); | |
} |
Isn’t this the same as array_column()?
@LucaRosaldi array_column() only works on arrays of objects after PHP 7.0, so this is a useful polyfill for users of PHP > 5.3 && PHP < 7.0
I've just found myself in that situation and used it =) thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Taken from Laravel project http://laravel.com/api/source-function-array_pluck.html#232
Example on similar wordpress function: http://codex.wordpress.org/Function_Reference/wp_list_pluck