Skip to content

Instantly share code, notes, and snippets.

@osazeblogger
Forked from ozh/example.php
Created April 25, 2022 15:43
Show Gist options
  • Save osazeblogger/e3d3df101a976a1dab91ed404af5c460 to your computer and use it in GitHub Desktop.
Save osazeblogger/e3d3df101a976a1dab91ed404af5c460 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment