William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

PHP: a lightweight function for output intermediate results

PHP: a lightweight function for output intermediate results.

In PHP, Except you use xdebug extension, the Intermediate results can be written in various ways. Here I list an effective, simply, convenient way which I used to make work easier. The purpose:

  1. For array and hash, using print_r() or var_dump() to output.
  2. For scalar variables, just simply use echo.
  3. Have the switch flag to open and close the output conveniently.

Here it is:

function __p($vars, $debug=true) {
 if (!$debug) return;
 if (is_array($vars) || is_object($vars)) {
  echo "<pre>";
  echo "</pre>";
 } else
  echo $vars . "<br>\n";

The default switch flag, ‘$debug’ is set to ‘true’ by default, so it can be used to output whatever you want to output:

// 1. for variable:
$sql = 'select ...'.mysql_real_escape_string($str);

//2. for function:
function foo($params) {...}

And later, if test ok, don’t need the output, just change the default switcher ‘$debug’ to false:

__p($sql, false);
__p(foo($params), false);

You can also set the ‘$debug’ as global constant variable, so as to control all the outputs by using a single switch flag.
As an advanced example, the following is a way of using HTTP request to control the output:

if ($__REQUEST['test']) {
  header('Content-Type: text/html; charset=utf-8');

At Browser’s URL part, everytime you add ‘test’ at end of the URI, like:


Instead of output all webpage, the output results will be redirect, and print out the intermediate results.
That is useful for test and debug purpose. Of course, the function can be enhanced to add more features and better output.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: