Skip to content

array_pluck

Rose Cox edited this page Mar 9, 2017 · 2 revisions

The array_pluck() function plucks an array of values from the given array. You pass in the keys that you want to find. Then the function walks through the array to find each and builds a new array for you.

Syntax:

array array_pluck( 
     array $subjectArray, 
     string|array $targetKeys,
     [ string $reKeyed ]
);

Examples

Examples will help you to understand how to use this function.

$users = array(
	array(
		'name'    => 'Tonya',
		'email'   => 'tonya@foo.com',
		'social'    => array(
			'twitter' => '@hellofromtonya',
		),
	),
	array(
		'name'    => 'Rose',
		'email'   => 'rose@foo.com',
		'social'    => array(
			'twitter' => '@rose',
		),
	),
	array(
		'name'    => 'Nate',
		'email'   => 'nate@foo.com',
		'social'    => array(
			'twitter' => '@nate',
		),
	),
);

array_pluck( $users, 'name' );
// Returns: array( 'Tonya', 'Rose', 'Nate' );

array_pluck( $users, 'email' );
// Returns: array( 'tonya@foo.com', 'rose@foo.com', 'nate@foo.com' ); 

array_pluck( $users, 'social.twitter' );
// Returns: array( '@hellofromtonya', '@rose', '@nate' ); 

array_pluck( $users, array( 'social', 'twitter' ) );
// Returns: array( '@hellofromtonya', '@rose', '@nate' ); 

Rekey

Yup, you can also rekey the returned array with the value of one of the elements. Let me show you:

array_pluck( $users, 'email', 'name' );
/** 
  Returns: 

	array(
		'Tonya' => 'tonya@foo.com',
		'Rose'  => 'rose@foo.com',
		'Nate'  => 'nate@foo.com',
	);
*/

array_pluck( $users, 'social.twitter', 'name' );
/** 
  Returns: 

	array(
		'Tonya' => '@hellofromtonya',
		'Rose'  => '@rose',
		'Nate'  => '@nate',
	);
*/

« Back to Array API

Clone this wiki locally