- gustavo's personal blog

Simplest way to render a collection with PHP


Rendering a collection of objects/elements retrieved from a database is a fairly common problem in web development and PHP. There are n ways to solve it, and I’ll present you a very simple and reusable one.

What we need to do is iterate over the collection and render each element using a view partial, and then print the final result. This can be solved using PHP’s output I hate SVN. I hate SVN. I REALLY HATE SVN.control functions, and variable variables. I used variable variables so I can iterate over the collection and name its elements in a meaningful way to be used in the view partial (e.g.: person, phone or product instead of ‘item’).

I don’t think I need to explain more. You can find the code below, fully commented for newbies. :)

 * @param  string       $partial    The path of the view partial
 * @param  array|object $collection An array or any object that implements the Iterator interface
 * @param  string       $elm        The name of the element of the collection to be used in the view
function render_collection($partial, $collection, $elm = 'item')
    // Turns on output buffering

    // Iterates over the collection, and assign each element to
    // a variable variable defined in the parameter $elm
    foreach ($collection as ${$elm})
        // Include the view partial, and render its contents
        include $partial . '.php';

    // Get buffer contents and delete current output buffer
    $result = ob_get_clean();

    // Print the rendered collection
    echo $result;

        array('name' => 'Bob',    'age' => '52'),
        array('name' => 'Mary',   'age' => '23'),
        array('name' => 'Joseph', 'age' => '43')
<?= $person['name'] ?> - <?= $person['age'] ?>
Bob - 52yo
Mary - 23yo
Joseph - 43yo