One of the patterns that I frequently run across when developing is trying to collect a column/attribute value from a collection of objects into an array. For example:
$ids = array();
foreach ($documents as $document) {
$ids[] = $document->name;
}
Am I the only one who runs into this? And does PHP have a way to solve this in fewer lines? I’ve looked but found nothing.
Since I use an MVC framework I have access to a BaseUtil class which contains common functions that don’t really fit in any specific classes. One solution proposed by a co-worker is:
class BaseUtil
{
public static function collect($collection, $property) {
$values = array();
foreach ($collection as $item) {
$values[] = $item->{$property};
}
return $values;
}
}
Then I can just do:
$ids = BaseUtil::collect($documents, 'name');
Not too shabby. Anyone else have any other ideas? And am I crazy or does this seem like a problem that PHP should have solved a long time ago?
You can use array_map() function for this purpose:
You might also consider the create_function() function for lambda functions if you don’t want to create a getName() function in the global namespace.
In PHP 5.3 you might even do: