Last Updated: December 26, 2018
·
5.135K
· leoj3n

var_dump vs. var_export

var_dump and var_export are useful functions for debugging PHP variables. However, most newbie tutorials only mention var_dump when they should be mentioning var_export as another possibility.

Let's say we want to print out the contents of $a which is defined:
$a = array( 1, 2, array( "a", "b", "c" ) );


using var_dump( $a ) we get:


array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}

as opposed to using var_export( $a ):


array (
  0 => 1,
  1 => 2,
  2 => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)

See what I mean? var_export is 100x more readable! But if you do need to know the types, use var_dump instead.

Edit per the comments:


And here is print_r( $a ):


Array
(
    [0] => 1
    [1] => 2
    [2] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )
)

5 Responses
Add your response

Nice tip!

over 1 year ago ·

The key difference is that var_export output valid PHP that you could write in other file (or eval) while var_dump is only for debugging

over 1 year ago ·

I find print_r is best for being readable, seeing as the documentation for it says it "Prints human-readable information about a variable"

over 1 year ago ·

@pyrech exactly - that's the comment I wanted to see :)

over 1 year ago ·

Also, var_dump shows information about the type of the variable. I think that each of them is for a particular purpose.

over 1 year ago ·