One or many

So, I get that there are probably better ways to handle this circumstance, but when working with legacy code, sometimes, it’s not up to you. I had a method that would be called with either one thing, or an array of these things. Approaching a context like this, the solution we came up with was (what I think is an) amazingly simple way to ensure if you’re sometimes receiving one thing or an array of things, you can handle both.

Check it out:

class Foo
    public function oneOrMany($input)
        if ( is_array( $input ) ) {
            return array_map(array($this,'oneOrMany'), $input);

        // Now do stuff to one $input only and return your results =]
        return $results;

There it is. And now hopefully I’ll remember this better next time I need something quick.


Leave a Reply...