PHP print_r Tree Viewer
    All articles

    print_r vs var_dump vs var_export: Which One Should You Use?

    5 min read

    Every PHP developer has typed print_r($thing); die; at some point. But PHP ships three built-in functions for looking inside a variable (print_r(), var_dump() and var_export()), and each prints something slightly different. Pick the wrong one and you can stare at a dump for ten minutes without noticing that the "missing" value was false the whole time.

    This guide runs the same data through all three and shows when each one is the right call.

    The short answer

    print_r() var_dump() var_export()
    Shows types No Yes, plus string lengths Implicitly (quotes, true, NULL)
    Can return a string Yes: print_r($x, true) No (needs output buffering) Yes: var_export($x, true)
    Output is valid PHP No No Yes
    Handles circular references Yes (*RECURSION*) Yes (*RECURSION*) No (warning, outputs NULL)
    Best for Quick look at structure, logs Checking exact types and values Fixtures, config files, copy-paste into tests

    If you only remember one thing: print_r for shape, var_dump for truth, var_export for code.

    Same data, three outputs

    Here's the array we'll use. It deliberately includes the values that cause confusion: a boolean true, a boolean false, a null and a float with no fractional part.

    $user = [
        'id'      => 42,
        'name'    => 'Alice',
        'active'  => true,
        'deleted' => false,
        'manager' => null,
        'score'   => 9.0,
        'roles'   => ['admin', 'editor'],
    ];
    Array
    (
        [id] => 42
        [name] => Alice
        [active] => 1
        [deleted] => 
        [manager] => 
        [score] => 9
        [roles] => Array
            (
                [0] => admin
                [1] => editor
            )
    
    )

    This is the easiest of the three to scan. Keys are in brackets, values follow =>, and nesting is shown by indentation. But look at what happened to the interesting values:

    • true became 1.
    • false and null both became nothing at all: [deleted] => and [manager] => look identical.
    • The float 9.0 became 9.
    • Strings have no quotes, so '42' (a string) and 42 (an int) print exactly the same.

    print_r converts every scalar to a string before printing it, and that's why those details disappear.

    var_dump()

    array(7) {
      ["id"]=>
      int(42)
      ["name"]=>
      string(5) "Alice"
      ["active"]=>
      bool(true)
      ["deleted"]=>
      bool(false)
      ["manager"]=>
      NULL
      ["score"]=>
      float(9)
      ["roles"]=>
      array(2) {
        [0]=>
        string(5) "admin"
        [1]=>
        string(6) "editor"
      }
    }

    Now every value carries its type: bool(false) and NULL are clearly different, and int(42) can't be mistaken for string(2) "42". You also get element counts for arrays (array(7)) and byte lengths for strings. string(5) "café" is a giveaway that you're looking at multibyte UTF-8, not a stray character.

    The price is length: var_dump uses roughly twice as many lines, which adds up fast on large structures.

    var_export()

    array (
      'id' => 42,
      'name' => 'Alice',
      'active' => true,
      'deleted' => false,
      'manager' => NULL,
      'score' => 9.0,
      'roles' => 
      array (
        0 => 'admin',
        1 => 'editor',
      ),
    )

    This output is valid PHP. Strings are quoted, booleans and null are written as literals, and the float keeps its .0. You can paste it straight into a test or a config file and it will evaluate back to the same array.

    When to use print_r()

    Use print_r when you want to understand the shape of the data: which keys exist, how deeply things are nested, how many items are in a list. It's the most compact and readable of the three, which is why it turns up in so many log files.

    It's also the easiest to log, because of its second argument:

    error_log(print_r($request->all(), true));

    With true, print_r returns the output as a string instead of echoing it. One caveat from the PHP manual: in return mode it uses output buffering internally, so you can't call it from inside an ob_start() callback.

    Objects work too. Visibility is shown in the key:

    User Object
    (
        [name] => Alice
        [email:protected] => [email protected]
        [password:User:private] => secret
    )

    Avoid print_r when you're debugging a condition that depends on the exact value, like if ($flag), === null or empty(). That's exactly where false, null, '' and '0' blur together.

    When to use var_dump()

    Use var_dump when you need to know what PHP actually has in memory: an int or a numeric string, false or null, a float or an int. A surprising number of "but the value is right there!" bugs turn out to be one of those.

    A few things worth knowing:

    • It accepts several arguments: var_dump($a, $b, $c); dumps each one in turn.

    • It always prints and has no return mode. To capture the output, wrap it in output buffering:

      ob_start();
      var_dump($order);
      $dump = ob_get_clean();
    • Xdebug changes it. With Xdebug's develop mode on, var_dump is replaced by a formatted HTML version that is also truncated by default (three levels deep, 128 children, 512 characters per string). If a nested value seems to be missing, check the xdebug.var_display_max_depth, xdebug.var_display_max_children and xdebug.var_display_max_data settings before assuming the data isn't there.

    • Objects show a handle number, like object(User)#1 (3), which helps you spot when two variables point to the same instance.

    When to use var_export()

    Use var_export when the dump is going to become code:

    • Test fixtures. Dump a real API response once, paste it into your test as the expected value.

    • Generated config files, a pattern used by plenty of frameworks:

      file_put_contents(
          'config.cache.php',
          '<?php return ' . var_export($config, true) . ';'
      );
    • Bug reports. A var_export snippet can be pasted and run by whoever picks up the issue.

    Its limits:

    • No circular references. If a structure refers to itself, var_export emits a warning (var_export does not handle circular references) and writes NULL in that spot. print_r and var_dump print *RECURSION* instead.
    • Objects export as __set_state() calls, such as \User::__set_state(array(...)). That only evaluates back if the class implements __set_state(). Plain stdClass objects are exported as (object) array(...) (PHP 7.3+), which works anywhere.

    What about json_encode?

    json_encode($data, JSON_PRETTY_PRINT) is a reasonable fourth option for data that's headed to (or came from) an API anyway, and every tool on earth can read JSON. But it's not a general-purpose debugger: it drops private and protected properties, turns associative and list arrays into different shapes ({} vs []), and silently returns false if any string contains invalid UTF-8 (unless you pass JSON_INVALID_UTF8_SUBSTITUTE, or JSON_THROW_ON_ERROR to get an exception instead).

    If you're on Laravel or Symfony, dump() and dd() (from Symfony's VarDumper component) combine the best of var_dump with a collapsible HTML view and are worth reaching for in those projects.

    A rule of thumb

    • "What does this look like?" → print_r
    • "Why is this condition false?" → var_dump
    • "I need to reuse this data in code." → var_export

    When the dump is huge

    All three are fine for a ten-line array. They get painful when you're looking at a few thousand lines of nested order data in a log file. print_r is usually what ends up there because it's the easiest to log, and it's also the hardest to search by eye.

    That's what the PHP print_r Tree Viewer is for: paste the output and you get a collapsible tree you can search by key, value or regex, all in your browser. If you're still at the "this is one giant unreadable line" stage, see how to make print_r output readable first.

    More from the blog