PHP Debugging - print_r vs var_dump vs var_export

PHP offers a number of methods that output a variable's contents which are useful when debugging code. I'm partial to var_dump for a few reasons I'll explain below.

Say we've got the following array and want to display its contents.

$test = array ('abc', false, true, 100, array('49'));

print_r() function - Displays human-readable output

Array
(
    [0] => abc
    [1] =>
    [2] => 1
    [3] => 100
    [4] => Array
        (
            [0] => 49
        )

)

So print_r tells us that this variable holds an array and shows us the values.  

But notice that the second and third elements don't reflect what we defined above.   The $test[1] value is shown as blank and $test[2] is shown as 1. Why is that?

PHP implicitly converts boolean values to strings in cases like these.   So false is converted to an empty string '' and boolean true is converted to '1'.

This can cause confusion if you don't understand what is happening.   This leads me to the next function.

var_dump() function - Displays values and types

 

array(5) {
  [0]=>
  string(3) "abc"
  [1]=>
  bool(false)
  [2]=>
  bool(true)
  [3]=>
  int(100)
  [4]=>
  array(1) {
    [0]=>
    string(2) "49"
  }
}

This is admittedly harder to read at first glance but the output gives you more information and accurately displays all values and types.

var_export() function  - Outputs PHP code

array (
  0 => 'abc',
  1 => false,
  2 => true,
  3 => 100,
  4 =>
  array (
    0 => '49',
  ),

This output can be useful if you need to parse this somewhere else in your script.

Official documentation

http://php.net/manual/en/function.print-r.php

http://php.net/manual/en/function.var-dump.php

http://php.net/manual/en/function.var-export.php