Last active
December 30, 2015 03:39
-
-
Save vespakoen/7770406 to your computer and use it in GitHub Desktop.
array_pluck
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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