tumblr page counter

Recursion

Posted by Whoppixian on Monday, 22 August, 2011, 1:36 AM

recursion

I've always hated recursion because my mind cannot cope with infinite loops and I can't find a way to think about it properly. I'm trying to figure out how to print an array of values using it. I want to compile the result into a string and return it and ...

Share |

Recursion

Posted by Whoppixian on Monday, 22 August, 2011, 1:36 AM

share [g+] share [fb] share [tw] I've always hated recursion because my mind cannot cope with infinite loops and I can't find a way to think about it properly. I'm trying to figure out how to print an array of values using it. I want to compile the result into a string and return it and use   to space it properly:

Recursion requires a base case, and a recursive step. If you are printing out an array, a good base case might be to check if the array is empty, and return. The recursive step would then pop off the first element and print it out.

function printArray($array) { //base case if(empty($array)) { return; } print_r(array_pop($array)); //recursive step return printArray($array)

function Process_Array($arr, $depth) { $retVal = ''; foreach($arr as $k => $v) { for($i = 0; $i < $depth; $i++) $retVal .= '  '; $retVal .= $k . ': '; if(is_array($v)) $retVal .= '
' . Process_Array($v, $depth + 1); else $retVal .= $v . '
'; } return $retVal; } $test = array( 'test1', 'test2', array( 'test3', array( 'test4', 'test5' ), 'test6' ), 'test7' ); echo Process_Array($test, 0); Output:

Not the answer you're looking for? Browse other questions tagged php arrays codeigniter recursion static-members or ask your own question. Hello World!

This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Share |