How to make a single function call handle one or many

I was browsing through Ning’s codebase the other day. I work directly with the code since I’ve customized a Ning network for one of Cloudspace’s clients in some subtle ways, just because he wanted it that way.

I really like the work they’ve done. Their codebase clearly has a lot of best practices.

I found one neat trick that was used to make a function a bit more versatile, in that it can easily be passed a single object, or an array of objects, with no sweat. If you’re interested, you can find an example of this in /widgets/activity/models/ActivityLogItem.php, in beforeDelete()

This isn’t their code, but here’s an example of the trick.

function eatPie($pie_id) {
    foreach( (is_array($pie_id) ? $pie_id : array($pie_id)) as $current_id) {
        // codez
    }
}

Really straightforward. If an array is passed in, each item in the array gets operated on. If a single item is passed in, it gets turned into an array, then each item in the array gets operated on. I also like how the tertiary statement gets used inline with the foreach. Of course, if you want a bit more code clarity, you can do it like this:

function eatPie($pie_id) {
    $pie_id = is_array($pie_id) ? $pie_id : array($pie_id);
    foreach($pie_id  as $current_id) {
        // codez
    }
}

2 thoughts on “How to make a single function call handle one or many”

Leave a Reply