IQ Development

If you're looking to hire a managed web development team in the UK, IQ Development is your solution.

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 ←

→ Comments have been disabled for this post ←

Out our window
Find a developer, get an iPod

To aid our search for highly talented developers, we're offering an iPod touch to any successful applicant for the job; or anyone who makes a recommendation.*

Find out who we’re after here

Blog categories
News