117

Here is the code for pulling the data for my array

<?php
    $link = mysqli_connect('localhost', 'root', '', 'mutli_page_form');

    $query = "SELECT * FROM wills_children WHERE will=73";

    $result = mysqli_query($link, $query) or die(mysqli_error($link));

    if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    if($row = mysqli_fetch_assoc($result)) {
        $data = unserialize($row['children']);
    }

    /* free result set */
    mysqli_free_result($result);
    }
?>

When I use print_r($data) it reads as:

Array ( [0] => Array ( [0] => Natural Chlid 1 [1] => Natural Chlid 2 [2] => Natural Chlid 3 ) ) 

I would like it to read as:

Natural Child 1
Natural Child 2
Natural Child 3

Hash
  • 4,647
  • 5
  • 21
  • 39
Xavier
  • 8,244
  • 18
  • 54
  • 85

18 Answers18

477

Instead of

print_r($data);

try

print "<pre>";
print_r($data);
print "</pre>";
Phenex
  • 4,781
  • 2
  • 13
  • 2
  • 4
    It is also worth mentioning that you can pass `true` as the second parameter to print_r to get the data as `string`. Now you can `return '
    '.print_r(User::all(), true);` from your routes file.
    – DutGRIFF Nov 05 '14 at 19:43
  • I like this answer too but the OP only wanted the Strings to print, and not the array indices (it seems like). And only 1-dimensional data. I usually only do this to check a recordset of data before I continue with a solution, so this solution works way better for stuff like that. – iopener Feb 08 '20 at 19:26
82
print("<pre>".print_r($data,true)."</pre>");
Shankar ARUL
  • 12,642
  • 11
  • 68
  • 69
54

I have a basic function:

function prettyPrint($a) {
    echo "<pre>";
    print_r($a);
    echo "</pre>";
}

prettyPrint($data);

EDIT: Optimised function

function prettyPrint($a) {
    echo '<pre>'.print_r($a,1).'</pre>';
}

EDIT: Moar Optimised function with custom tag support

function prettyPrint($a, $t='pre') {echo "<$t>".print_r($a,1)."</$t>";}
beppe9000
  • 1,056
  • 1
  • 13
  • 28
ditto
  • 5,917
  • 10
  • 51
  • 88
  • 7
    Best answer so far, and you can even optimize it more if it's used very often with comma : `echo '
    ',print_r($a,1),'
    ';`
    – Darkendorf Nov 14 '14 at 08:14
33

Try this:

foreach($data[0] as $child) {
   echo $child . "\n";
}

in place of print_r($data)

Brian Driscoll
  • 19,373
  • 3
  • 46
  • 65
  • thanks for the response but it prints out the data as "Array" – Xavier Mar 22 '11 at 14:56
  • 1
    `"; }?>` this worked great thanks Brian ! – Xavier Mar 22 '11 at 14:58
  • 65
    why on earth is this the chosen answer when
     is the obvious choice?
    – cantsay Feb 26 '14 at 15:14
  • > why on earth is this the chosen answer? Engineers :-) – Salil Jul 14 '16 at 06:12
  • 2
    This will not work if you have a multidimensional array. – scorgn Dec 06 '16 at 20:04
  • 3
    @Alesana Yep, but OP didn't have a multidimensional array. I think as others have commented on this answer the way you want to go is `
    print_r($data)
    `. Always fun to see a new comment on a 5+ year old answer though! :)
    – Brian Driscoll Dec 06 '16 at 20:07
  • 2
    Ah, in my case I was working with a multidimensional array. I haven't left a comment before so when I saw no one else had pointed this out I thought it might be a perfect opportunity! – scorgn Dec 06 '16 at 20:13
  • @BrianDriscoll, how about another 4 years :D? Thanks for pointing out Pre, pre, though. I don't search much further than the answer most of the time. – Livo Jun 19 '20 at 21:34
24

I think that var_export(), the forgotten brother of var_dump() has the best output - it's more compact:

echo "<pre>";
var_export($menue);
echo "</pre>";

By the way: it's not allway necessary to use <pre>. var_dump() and var_export() are already formatted when you take a look in the source code of your webpage.

RavatSinh Sisodiya
  • 1,596
  • 1
  • 20
  • 42
Hexodus
  • 12,361
  • 6
  • 53
  • 72
  • I agree about var_export, but I've had to combine it with
     because it wasn't outputting the results in the proper format.
    – Chaya Cooper Mar 26 '15 at 16:47
  • 3
    @Chaya-Cooper It's not properly formatted on the displayed page, but I think Hexodus meant it's formatted "in the _source code_ of your web page" -> try menu "view source", or Ctrl-U in Firefox – fpierrat Apr 02 '15 at 14:56
  • 1
    One benefit of this approach is that the output is formatted as valid PHP, so you could copy/paste it right back into your code if you wanted to. – Sean the Bean Feb 27 '18 at 15:44
18

if someone needs to view arrays so cool ;) use this method.. this will print to your browser console

function console($obj)
{
    $js = json_encode($obj);
    print_r('<script>console.log('.$js.')</script>');
}

you can use like this..

console($myObject);

Output will be like this.. so cool eh !!

enter image description here

shakee93
  • 4,976
  • 2
  • 28
  • 32
6
foreach($array as $v) echo $v, PHP_EOL;

UPDATE: A more sophisticated solution would be:

 $test = [
    'key1' => 'val1',
    'key2' => 'val2',
    'key3' => [
        'subkey1' => 'subval1',
        'subkey2' => 'subval2',
        'subkey3' => [
            'subsubkey1' => 'subsubval1',
            'subsubkey2' => 'subsubval2',
        ],
    ],
];
function printArray($arr, $pad = 0, $padStr = "\t") {
    $outerPad = $pad;
    $innerPad = $pad + 1;
    $out = '[' . PHP_EOL;
    foreach ($arr as $k => $v) {
        if (is_array($v)) {
            $out .= str_repeat($padStr, $innerPad) . $k . ' => ' . printArray($v, $innerPad) . PHP_EOL;
        } else {
            $out .= str_repeat($padStr, $innerPad) . $k . ' => ' . $v;
            $out .= PHP_EOL;
        }
    }
    $out .= str_repeat($padStr, $outerPad) . ']';
    return $out;
}

echo printArray($test);

This prints out:

    [
        key1 => val1
        key2 => val2
        key3 => [
            subkey1 => subval1
            subkey2 => subval2
            subkey3 => [
                subsubkey1 => subsubval1
                subsubkey2 => subsubval2
            ]
        ]
    ]
Yaronius
  • 784
  • 3
  • 17
  • 34
3

This may be a simpler solution:

echo implode('<br>', $data[0]);
Beta Projects
  • 426
  • 1
  • 8
  • 18
3

print_r() is mostly for debugging. If you want to print it in that format, loop through the array, and print the elements out.

foreach($data as $d){
  foreach($d as $v){
    echo $v."\n";
  }
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
3

This tries to improve print_r() output formatting in console applications:

function pretty_printr($array) {

  $string = print_r($array, TRUE);

  foreach (preg_split("/((\r?\n)|(\r\n?))/", $string) as $line) {

    $trimmed_line = trim($line);

    // Skip useless lines.
    if (!$trimmed_line || $trimmed_line === '(' || $trimmed_line === ')' || $trimmed_line === 'Array') {
      continue;
    }

    // Improve lines ending with empty values.
    if (substr_compare($trimmed_line, '=>', -2) === 0) {
      $line .=  "''";
    }

    print $line . PHP_EOL;
  }
}

Example:

[activity_score] => 0
[allow_organisation_contact] => 1
[cover_media] => Array
        [image] => Array
                [url] => ''
        [video] => Array
                [url] => ''
                [oembed_html] => ''
        [thumb] => Array
                [url] => ''
[created_at] => 2019-06-25T09:50:22+02:00
[description] => example description
[state] => published
[fundraiser_type] => anniversary
[end_date] => 2019-09-25
[event] => Array
[goal] => Array
        [cents] => 40000
        [currency] => EUR
[id] => 37798
[your_reference] => ''
Pere
  • 1,647
  • 3
  • 27
  • 52
2

I assume one uses print_r for debugging. I would then suggest using libraries like Kint. This allows displaying big arrays in a readable format:

$data = [['Natural Child 1', 'Natural Child 2', 'Natural Child 3']];
Kint::dump($data, $_SERVER);

enter image description here

zendka
  • 1,074
  • 12
  • 11
2

One-liner for a quick-and-easy JSON representation:

    echo json_encode($data, JSON_PRETTY_PRINT);

If using composer for the project already, require symfony/yaml and:

    echo Yaml::dump($data);
TIH
  • 76
  • 1
  • 3
1
<?php 
//Make an array readable as string
function array_read($array, $seperator = ', ', $ending = ' and '){
      $opt = count($array);
      return $opt > 1 ? implode($seperator,array_slice($array,0,$opt-1)).$ending.end($array) : $array[0];
}
?>

I use this to show a pretty printed array to my visitors

3eighty
  • 199
  • 2
  • 5
1

Very nice way to print formatted array in php, using the var_dump function.

 $a = array(1, 2, array("a", "b", "c"));
 var_dump($a);
Muhammad
  • 3,169
  • 5
  • 41
  • 70
1

I use this for getting keys and their values $qw = mysqli_query($connection, $query);

while ( $ou = mysqli_fetch_array($qw) )
{
    foreach ($ou as $key => $value) 
    {
            echo $key." - ".$value."";
    }
    echo "<br/>";
}
uutsav
  • 389
  • 5
  • 16
1

I would just use online tools.

1
echo '<pre>';
foreach($data as $entry){
    foreach($entry as $entry2){
        echo $entry2.'<br />';
    }
}
powtac
  • 40,542
  • 28
  • 115
  • 170
0

For single arrays you can use implode, it has a cleaner result to print.

<?php
$msg = array('msg1','msg2','msg3');
echo implode('<br />',$msg);
echo '<br />----------------------<br/>';

echo nl2br(implode("\n",$msg));
echo '<br />----------------------<br/>';
?>

For multidimensional arrays you need to combine with some sort of loop.

<?php
$msgs[] = $msg;
$msgs[] = $msg;
$msgs[] = $msg;
$msgs[] = $msg;
$msgs[] = $msg;
foreach($msgs as $msg) {
    echo implode('<br />',$msg);
    echo '<br />----------------------<br/>';
}
?>
mjaning
  • 71
  • 1
  • 4