This question already has an answer here:
Let's say that I have an array like this:
$people = array(
array(
'name' => 'Bob',
'job' => 'Carpenter'
),
array(
'name' => 'George',
'job' => 'Programmer'
),
array(
'name' => 'Clint',
'job' => 'Actor'
)
);
And I want to know the names of all of these people.
I know that I could do this:
$names = array();
foreach($people as $person)
$names[] = $person['name'];
But let's say that I'm lazy, so I create a function for it instead:
/**
* Returns an Array of Values paired with the specified $key
* in the $array of Associative Arras.
*
* @param array $array The Array of Associative Arrays.
* @param string $key The Key within each Associative Array to retrieve the Value
*
* @return array The Array of Keyed Values within the Array of Arrays.
*/
function array_keyed_values($array, $key)
{
$values = array();
foreach($array as $associative)
if(array_key_exists($key, $associative))
$values[] = $associative[$key];
return $values;
}
Cool, I've officially solved my problem. I just need to do:
$names = array_keyed_values($people, 'name');
To get:
(Bob, George, Clint)
And I'm done.
However, I doubt that I'm the first person to need this kind of functionality. Given that PHP is littered with a plethora of quirky functions that do weird things, I'm wondering if something like this already exists.
Yes, I know, I'm only saving myself 10 to 20 lines of code by not writing the function I need, but in a framework that uses tons of files, having to constantly include a library to do something this simple tends to get a little tedious.
I've tried searching around for this, but I might not be using the right keywords. Something like this involves arrays, keys, and values, so searching for that type of stuff tends to constantly point me to array_keys()
or array_values()
, neither of which is what I want.
NOTE:
For the particular application I'm using, the ordering of the values when returned does not matter.
Also, the version of PHP I'm using is 5.3. If a later version of PHP adds this functionality, please state that in your answer.
EDIT:
The following solution worked in this scenario:
$result = array_map(function($v) { return $v['name']; }, $people);
However, I also used this to solve a similar problem where I had an array of objects (where the nested arrays where the objects, and the keys were the variables). By slightly modifying the code above, I solved that problem too:
$result = array_map(function($v) { return $v->name; }, $people);
While array_column()
works for my scenario (if I were using PHP 5.5+ instead of PHP 5.3), it wouldn't work for the modified solution above (Hence the edit).
</div>