We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Get list of records, with database ID as key

I want a quick and easy way to get a list of values from a table as an associative array, in wich the keys would be the ID of the table, and the value, any field of the database.

I mean, i want to do this with a one-liner:

    $projects = [];
    foreach (Projects::find(['columns' => ['id', 'name']])->toArray() as $key => $project) 
        $projects[$project['id']] = $project['name'];

But I can't find a practical way to do it, I also know CakePHP, and with cake you would do something like this:


(Having previously defined the key and value fields in the model)

Any suggestions? If it's not implemented, I think it would be a really cool feature to have :D


It's not implemented. I always have custom method in the model I need, because I have to join 1-2 tables before I get the desired output.

Here is a very simple method you can put in your BaseModel and use it everywhere:

public static function toList($where = '', $columns) 
    $items = self::find([
        'conditions' => $where,
        'columns' => $columns

    $collection = [];
    foreach ($items as $item) {
        $collection[$item->{$columns[0]}] = $item->{$columns[1]};
    return $collection;

How to use:

$items = \Models\Countries::toList('id > 100', ['id', 'code']);
edited May '17


$projects = array_walk(Projects::find(['columns' => ['id', 'name']]), function(&$v, &$k) { $k = $v['id']; $v = $v['name']; });

Everything can be a one liner if you are brave enough :D

Awesome guys! Handy snippets, Thanks!

and you are sure you can rewrite the array key?


$projects = array_walk(Projects::find(['columns' => ['id', 'name']]), function(&$v, &$k) { $k = $v['id']; $v = $v['name']; });