Design Ontap

If you're looking for UK based web development fulfilment, Design Ontap are here to help. Call us now: 0845 644 7782

Blog categories

  1. Technology (5)
  2. General web (1)
  3. Industry (3)
  4. Business (1)
  5. PHP (1)

Browse all posts

Handy debug function

Posted by: Tim Southcombe on the: 20 Sep 2007

Ever been stuck trying to get the contents of a PHP array out to a browser because of styling and readability?

Well here's an handy little function we've been using in projects for a while. It nicely outputs your array or object into the flow of data making life that little easier. There are loads of vars that you can pop into the function to configure the display too and get around CSS styling issues (← indicates long lines that have been wrapped to the next line).

function debug($var = NULL)
{ 
  $var = print_r($var, true);
  foreach (func_get_args() as $key => $value)
  {
    if (is_bool($value) && $value === true && ←
        !isset($plain)) $plain = true;
    if (is_string($value) && !empty($value) && ←
        !isset($title)) $title = $value;
    if (is_int($value) && !empty($value) && ←
        !isset($font_size)) $font_size = $value;
    } 
  if (!isset($plain))
  {
    $var = preg_replace_callback("/[[a-zA-Z0-9 _]*]/", ←
        create_function('$matches', ←
        'return "[<span style="color:#990000;"><b>". ←
        substr($matches[0], 1, strlen($matches[0])-2) ←
        ."</b></span>]";'), $var);
    $var = preg_replace_callback("/=>.*/", ←
        create_function('$matches', 'return "=> ←
        <span style="color:#003399;"><b>" ←
        . trim(substr($matches[0], 3, ←
        strlen($matches[0]))) ."</b></span>";'), $var);
    $var = preg_replace("/)|(/", "<b>\0</b>", $var);
    if (isset($title) && !empty($title)) ←
        $var = preg_replace("/^Array/i", ←
        "<span style="color:#003399; ←
        font-weight:bold;">\0:</span> ←
        <i><b>{$title}</b></i>", $var);
    else $var = preg_replace("/^Array/", ←
        "<span style="color:#003399;"> ←
        <b>\0</b></span>", $var); 
    echo "<pre style="font:". (isset($font_size) ←
        ? $font_size : "13") ."px 'Courier New', ←
        Courier, mono; background:#F3F3F3; ←
        width:95%; display:block; padding:10px; ←
        margin:10px; border:2px solid #A5A5A5;">" ←
        . $var . "</pre>"; 
  }
  else
  {
    if (isset($title) && !empty($title)) ←
        $var = preg_replace("/^Array/i", ←
         "\0: {$title}", $var);
    echo "<pre>". $var . "</pre>";
  }
}
View comments (0) | View trackbacks (0) | Permalink | Trackback

There are no comments for this post

Latest News

Site Foundry reaches its first birthday // 20 Sep 2007

After two full point versions and a number of upgrades under the...

1

Web development with a nicely designed exterior