who can do this without the recursion

From: Date: Tue, 05 Jul 2005 10:48:49 +0000
Subject: who can do this without the recursion
Groups: php.general 
Request: Send a blank email to php-general+get-218116@lists.php.net to get a copy of this message
hi everyone, I have a function which recursively loops an assoc array in order to build an HTML string containing hidden <input> elements that repesent the key/values passed in the array ... I know this can be done without recursion but I'm having a brainfreeze, anyone care to share some tips on replacing the recursion with some kind of stack based solution (the idea being that I want to remove the overhead of the recursive calls to the function if possible ... I'm looking to get a better understanding of alternatives to recursion in general rather than in this specific example, so come people show us what you can do! :-) example: function rec_build_hidden_inputs($args = array(), $prefix = '') {
    static $inputTpl = "<input type="hidden" name="%s" value="%s" />\n";
    $_contents = '';
    foreach ($args as $key => $val) {
        $nextPrefix = $prefix > ''
                    ? "{$prefix}[{$key}]";
                    : $key
                    ;
        $_contents .= is_array($val)
                    ? rec_build_hidden_inputs($val, $nextPrefix)
                    : sprintf($inputTpl, $nextPrefix, $key)
                    ;
    }
    return $_contents;
} rgds, Jochem PS - do ya think I can copyright this?: = ? : ; nah, didn't think so - none the less you might be surprised how many people it annoys ;-)

« previous php.general (#218116) next »