I'm wondering if my algorithm is tail recursive; I've just made this function to pretty print an array in PHP:
function get_pretty_output($value, $first=true, $indent = ''){
if (!is_array($value)) { return $value.PHP_EOL; }
if (empty($value)) { if ($first) { return 'Array()'.PHP_EOL; } else { return preg_replace('/ /', '', $indent, 1).')'.PHP_EOL; }}
if ($first) {
$output = 'Array'.PHP_EOL.$indent.'('.PHP_EOL;
$indent .=' ';
$first = false;
} else {
$output = '';
}
reset($value);
$key = key($value);
return $output .= $indent .
'[' .
$key .
'] => ' .
get_pretty_output(array_shift($value), true, $indent) .
get_pretty_output($value, $first, $indent);
}
because neither
$pretty_string = print_r($array, true);
nor
ob_start();
var_dump($array);
$pretty_string = ob_get_contents();
ob_end_clean();
seem to work when the client disconnects even with ignore_user_abort(true)
(PHP 5.6).
I don't even know if PHP benefits from tail recursion (I was told it doesn't), but anyway I would like to know if this would be a valid example. I don't think so (it needs to save the function context to use on the second call), but I don't seem to be able to find an equivalent tail recursive algorithm. Is there a method I can follow?