23

How can I print an array so instead of being all a single line such as:

Array ( [0] => Array ( [Palabra] => correr [Tipo] => Verbo ) [1] => Array ( [Palabra] => es [Tipo] => Verbo [PersonaSujeto] => tercera [CantidadSujeto] => singular [Tiempo] => presente ) 

It displays something more readable like this or similar:

Array ( 
    [0] => Array ( 
        [Palabra] => correr
        [1] => Array ( 
             [Tipo] => Verbo 
             [Tiempo] => Infinitivo) )
    [1] => Array ( 
        [Palabra] => es 
        [Tipo] => Verbo 
        [PersonaSujeto] => tercera 
        [CantidadSujeto] => singular 
        [Tiempo] => presente ) 
lisovaccaro
  • 32,502
  • 98
  • 258
  • 410

8 Answers8

70

It is printed out with a line break, but in HTML line breaks are meaningless. You can do one of 2 things:

  1. Tell the browser it's not an HTML document, but a text, by placing the following code before any output is sent:

    header('Content-type: text/plain');
    
  2. Simply have <pre> tags around the printed array:

    echo '<pre>'; print_r($array); echo '</pre>';
    
insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
12

I love code highlighting. This example displays the beatified array with highlighted code

<?php
$debug_data = array(1,2,5,6,8,7,'aaa');

echo str_replace(array('&lt;?php&nbsp;','?&gt;'), '', highlight_string( '<?php ' .     var_export($debug_data, true) . ' ?>', true ) );
?>

enter image description here

FDisk
  • 8,493
  • 2
  • 47
  • 52
3

If you wrap the output of functions like print_r, var_dump, and var_export in a <pre> tag, it will be relatively nicely formatted.

The reason is because the output of the functions is plain text, but when you look at it in a browser, the browser considers it HTML. The new line characters in the plaintext output are not meaningful to HTML, as new lines are ignored.

To see this in action, try viewing the source - you'll see the nicely formatted output there.

The pre HTML tag tells a browser "everything inside of this block is pre-formated". New lines are treated as new lines, spacing is respected (HTML also doesn't care about sequences of spaces).

So, you're left with something like this:

echo '<pre>'.print_r($my_array).'</pre>';

Instead of doing that all over my code, I like to use a composite function like this (I call it print_p so it is like typing print_r)

function print_p($value = false, $exit = false, $return=false, $recurse=false) {
    if ($return === true && $exit === true)
        $return = false;
    $tab = str_repeat("&nbsp;", 8);
    if ($recurse == false) {
        $recurse = 0;
        $output = '<div style="width:100%; border: 2px dotted red; background-color: #fbffd6; display: block; padding: 4px;">';
        $backtrace = debug_backtrace();
        $output .= '<b>Line: </b>'.$backtrace[0]['line'].'<br>';
        $output .= '<b>File: </b> '.$backtrace[0]['file'].'<br>';
        $indent = "";
    } else {
        $output = '';
        $indent = str_repeat("&nbsp;", $recurse * 8);
    }
    if (is_array($value)) {
        if ($recurse == false) {
            $output .= '<b>Type: </b> Array<br>';
            $output .= "<br>array (<br>";
        } else {
            $output .= "array (<br>";
        }
        $items = array();
        foreach ($value as $k=>$v) {
            if (is_object($v) || is_array($v))
                $items[] = $indent.$tab."'".$k."'=>".print_p($v, false, true, ($recurse+1));
            else
                $items[] = $indent.$tab."'".$k."'=>".($v===null ? "NULL" : "'".$v."'");
        }
        $output .= implode(',<br>', $items);
        if ($recurse == false)
            $output .= '<br>)';
        else
            $output .= '<br>'.$indent.')';
    } elseif (is_object($value)) {
        if ($recurse == false) {
            $output .= '<b>Type: </b> Object<br>';
            $output .= '<br>object ('.get_class($value).'){'."<br>";
        } else {
            $output .= "object (".get_class($value)."){<br>";
        }

        // needed conditional because base class function dump is protected
        $vars = get_object_vars($value);
        $vars = (is_array($vars) == true ? $vars : array());

        $items = array();
        foreach ($vars as $k=>$v) {
            if (is_object($v) || is_array($v))
                $items[] = $indent.$tab."'".$k."'=>".print_p($v, false, true, ($recurse+1));
            else
                $items[] = $indent.$tab."'".$k."'=>".($v===null ? "NULL" : "'".$v."'");
        }
        $output .= implode(',<br>', $items);
        $vars = get_class_methods($value);
        $items = array();
        foreach ($vars as $v) {
            $items[] = $indent.$tab.$tab.$v;
        }
        $output .= '<br>'.$indent.$tab.'<b>Methods</b><br>'.implode(',<br>', $items);
        if ($recurse == false)
            $output .= '<br>}';
        else
            $output .= '<br>'.$indent.'}';
    } else {
        if ($recurse == false) {
            $output .= '<b>Type: </b> '.gettype($value).'<br>';
            $output .= '<b>Value: </b> '.$value;
        } else {
            $output .= '('.gettype($value).') '.$value;
        }
    }
    if ($recurse == false)
        $output .= '</div>';
    if ($return === false)
        echo $output;
    if ($exit === true)
        die();
    return $output;
}

... then you do this:

print_p($my_array);

...and get the output:

enter image description here

This is nice because it a) will take any type of variable, objects, arrays, strings, and b) tell you where the output is coming from. It can get really frustrating if you lose track of where you had put a debugging message and have to spend time searching all over for it! :)

Chris Baker
  • 49,926
  • 12
  • 96
  • 115
2

This is the best friend of a PHP programmer:

function pa($value, $exit = true){
  echo "<pre>";
  print_r($value);
  echo "</pre>";
  if($exit){
    exit();
  }
}

If you need use like this:

pa($arr);

or

pa($obj);

If you don't want to exit

pa($obj, false);
Serdar D.
  • 3,055
  • 1
  • 30
  • 23
1

A different/quick way to display one-line format in html:

echo nl2br(print_r($myarray, true));

user6096790
  • 380
  • 4
  • 8
0

All the above answers are good. I like to include a debug() php function in my functions so anywhere in my app I can just call debug($my_array); to dump the array to the screen (or the html), with some nice readability formatting. Here it is on github.

Of course these days most servers and frameworks have their own built-in version of something like this, but for building something from scratch this works.

0

Add <pre>

Example:

<pre>
<?php
    print_r($array);
?>
<pre>
SlavaNov
  • 2,447
  • 1
  • 18
  • 26
0
  1. As other answers say: There are already newlines and tabs in the print_r output. And you can see it using <pre> or seeing as plain text.

  2. You may install xdebug to make output of print_r more readable

RiaD
  • 46,822
  • 11
  • 79
  • 123