Search code examples
phparraysvar-dump

Make var_dump look pretty


I have a simple $_GET[] query var set for showing testing data when pulling down queries from the DB.

<?php if($_GET['test']): ?>
  <div id="test" style="padding: 24px; background: #fff; text-align: center;">  
    <table>
      <tr style="font-weight: bold;"><td>MLS</td></tr>
      <tr><td><?php echo KEY; ?></td></tr>
      <tr style="font-weight: bold;"><td>QUERY</td></tr>
      <tr><td><?php echo $data_q; ?></td></tr>
      <tr style="font-weight: bold;"><td>DATA</td></tr>
      <tr><td><?php var_dump($data); ?></td></tr>
    </table>    
</div>
<?php endif; ?>

When I do var_dump, as expected it's this big array string that is all smushed together. Is there a way to add in line breaks at least for this or display the var_dump in a way that's more readable? I'm open to jQuery suggestions on manipulating the string after it's posted.


Solution

  • I really love var_export(). If you like copy/paste-able code, try:

    echo '<pre>' . var_export($data, true) . '</pre>';
    

    Or even something like this for color syntax highlighting:

    highlight_string("<?php\n\$data =\n" . var_export($data, true) . ";\n?>");
    

    Reusable function:

    function highlight_array($array, $name = 'var') {
        highlight_string("<?php\n\$$name =\n" . var_export($array, true) . ";\n?>");
    }
    

    You can do the same with print_r(). For var_dump() you would just need to add the <pre> tags:

    echo '<pre>';
    var_dump($data);
    echo '</pre>';