WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/wp list pluck

Description

Pluck a certain field out of each object in a list

Usage

<?php wp_list_pluck$list$field$index_key null ); ?>

Parameters

$list
(array) (required) A list of objects or arrays
Default: None
$field
(mixed) (required) A field from the object to place instead of the entire object
Default: None
$index_key
(mixed) (optional) Field from the object to use as keys for the new array. Added in 4.0
Default: null

Return Values

(array) 
Array of found values. If $index_key is set, an array of found values with keys corresponding to $index_key.

Examples

The following is an array listing foods:

<?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',
	),
);
?>

The names of each food can easily be "plucked" from the $foods array using wp_list_pluck().

<?php $food_names = wp_list_pluck( $foods, 'name' ); ?>

$food_names will now contain a numerically indexed array of food names equivalent to:

<?php
array(
	'Banana',
	'Apple',
	'Lettuce',
	'Apple'
);
?>

Since version 4.0 you may define a third parameter named $index_key to define a specific field of the list to be used as key. The following snippet would get listings in the form of id => name.

<?php $food_names = wp_list_pluck( $foods, 'name', 'id' ); ?>

The resulting $food_names array:

<?php
array(
	4 => 'Banana',
	5 => 'Apple',
	2 => 'Lettuce',
	7 => 'Apple'
);
?>

Change Log

Since: 3.1

Source File

wp_list_pluck() is located in wp-includes/functions.php