Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP print array with one key per line so it's easier on the eyes?

Tags:

arrays

php

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 ) 
like image 735
lisovaccaro Avatar asked Dec 16 '11 22:12

lisovaccaro


People also ask

How do I print the value of an array in one line?

Print Array in One Line with Java StreamsArrays. toString() and Arrays. toDeepString() just print the contents in a fixed manner and were added as convenience methods that remove the need for you to create a manual for loop.

How do I print an array on separate lines?

To print the array elements on a separate line, we can use the printf command with the %s format specifier and newline character \n in Bash. @$ expands the each element in the array as a separate argument. %s is a format specifier for a string that adds a placeholder to the array element.

How do I print an array of elements in a new line?

To print each word on a new line, we need to use the keys “%s'\n”. '%s' is to read the string till the end. At the same time, '\n' moves the words to the next line. To display the content of the array, we will not use the “#” sign.

What are the 3 types of PHP arrays?

Create an Array in PHP In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.


3 Answers

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>';
    
like image 138
Madara's Ghost Avatar answered Oct 10 '22 05:10

Madara's Ghost


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

like image 27
FDisk Avatar answered Oct 10 '22 05:10

FDisk


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! :)

like image 3
Chris Baker Avatar answered Oct 10 '22 05:10

Chris Baker