Skip to content

Instantly share code, notes, and snippets.

@vespakoen
Last active December 30, 2015 03:39
Show Gist options
  • Save vespakoen/7770406 to your computer and use it in GitHub Desktop.
Save vespakoen/7770406 to your computer and use it in GitHub Desktop.
array_pluck
<?php
/**
* Pluck an array of values from an array.
*
* @param array $array
* @param string $value
* @param string $key
* @return array
*/
function array_pluck($array, $value = null, $key = null)
{
$results = array();
foreach ($array as $item)
{
if(is_null($value))
{
$itemValue = $item;
}
else
{
$itemValue = is_object($item) ? $item->{$value} : $item[$value];
}
// If the key is "null", we will just append the value to the array and keep
// looping. Otherwise we will key the array using the value of the key we
// received from the developer. Then we'll return the final array form.
if (is_null($key))
{
$results[] = $itemValue;
}
else
{
$itemKey = is_object($item) ? $item->{$key} : $item[$key];
$results[$itemKey] = $itemValue;
}
}
return $results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment