Debug a variable


/ Published in: PHP
Save to your folder(s)

When working in PHP I sometimes want to know exactly what is in a variable. This is easy enough to find out, but having this function around it is even easier, as it includes the HTML pre tag making it easier to read, and it allows you to choose how it should be debugged (defaults to using print_r()).


Copy this code and paste it in your HTML
  1. if ( ! function_exists('debug'))
  2. {
  3. function debug($var, $fn='print_r')
  4. {
  5. if (function_exists($fn))
  6. {
  7. echo '<pre>', $fn($var), '</pre>';
  8. }
  9. else
  10. {
  11. echo '<pre>The function ', $fn, '() does not exist. Falling back to',
  12. ' print_r().<br /><br />', print_r($var), '</pre>';
  13. }
  14. }
  15. }
  16.  
  17. // Example
  18.  
  19. debug(array('test1',123));
  20.  
  21. /*
  22. <pre>Array
  23. (
  24.   [0] => test1
  25.   [1] => 123
  26. )
  27. 1</pre>
  28. */

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.