Question

In PHP, I wrote a function to indent echo'ed lines based on the depth in the debug backtrace:

function echon($string){
  $nest_level = count(debug_backtrace()) - 1; // minus one to ignore the call to *this* function
  echo str_repeat("  ", $nest_level) . $string . "\n";
}

I use it at the beginning of every function to help debug; eg,
echon("function: Database->insert_row");

I want to write a similar function for print_r, but I'm unsure how. After looking at the docs for print_r I learned that passing it the optional parameter true makes it return a string, but that string is strangely formatted; if I flat out echo it, it looks like this:

print_r return string is:

Array
(
    [uid] => 1
    [username] => user1
    [password] => $2y$10$.XitxuSAaePgUb4WytGfKu8HPzJI94Eirepe8zQ9d2O1oOCgqPT26
    [firstname] => devon
    [lastname] => parsons
    [email] => 
    [group] => 
    [validated] => 0
    [description] => 
    [commentscore] => 0
    [numberofposts] => 0
    [birthdate] => 1992-04-23
    [location] => 
    [signupdate] => 0000-00-00
    [personallink] => 
)

So I originally thought it would return a single line response that I could manually explode and indent in the same manner, but it's multi line and I don't know what to look for next. I looked around the php doc for strings to see if there was some way to extract a single line at a time, or to explode it based on new lines, but I found nothing and googling didn't turn up anything similar.

Question: How can I prepend whitespace to the result of print_r?

Edit: Example desire output (assuming I'm calling my function from a depth of 1)

    Array
    (
        [uid] => 1
        [username] => user1
        [password] => $2y$10$.XitxuSAaePgUb4WytGfKu8HPzJI94Eirepe8zQ9d2O1oOCgqPT26
        [firstname] => devon
        [lastname] => parsons
        [email] => 
        [group] => 
        [validated] => 0
        [description] => 
        [commentscore] => 0
        [numberofposts] => 0
        [birthdate] => 1992-04-23
        [location] => 
        [signupdate] => 0000-00-00
        [personallink] => 
    )
Was it helpful?

Solution

This should do what you want:

function print_rn($array)
{
    $nest_level = count(debug_backtrace()) - 1; // minus one to ignore the call to *this* function
    $lines = explode("\n", print_r($array, true));

    foreach ($lines as $line) {
        echo str_repeat("  ", $nest_level) . $line . "\n";
    }
}

Explanation:

print_r takes a second argument, which allows you to return the value instead of printing it out. Then, you can use the explode function (which is PHP's string_split function) to split the returned string into an array, at every newline. Now you have an array of lines.

With an array of lines, it's simple to iterate over each one and print it using the appropriate amount of whitespace.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top