-
Notifications
You must be signed in to change notification settings - Fork 1
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.
array array_pluck(
array $subjectArray,
string|array $targetKeys,
[ string $reKeyed ]
);
Examples will help you to understand how to use this function.
$users = array(
array(
'name' => 'Tonya',
'email' => '[email protected]',
'social' => array(
'twitter' => '@hellofromtonya',
),
),
array(
'name' => 'Rose',
'email' => '[email protected]',
'social' => array(
'twitter' => '@rose',
),
),
array(
'name' => 'Nate',
'email' => '[email protected]',
'social' => array(
'twitter' => '@nate',
),
),
);
array_pluck( $users, 'name' );
// Returns: array( 'Tonya', 'Rose', 'Nate' );
array_pluck( $users, 'email' );
// Returns: array( '[email protected]', '[email protected]', '[email protected]' );
array_pluck( $users, 'social.twitter' );
// Returns: array( '@hellofromtonya', '@rose', '@nate' );
array_pluck( $users, array( 'social', 'twitter' ) );
// Returns: array( '@hellofromtonya', '@rose', '@nate' );
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' => '[email protected]',
'Rose' => '[email protected]',
'Nate' => '[email protected]',
);
*/
array_pluck( $users, 'social.twitter', 'name' );
/**
Returns:
array(
'Tonya' => '@hellofromtonya',
'Rose' => '@rose',
'Nate' => '@nate',
);
*/