Difference between var_dump,var_export & print_r

Php

Php Problem Overview


What is the difference between var_dump, var_export and print_r ?

Php Solutions


Solution 1 - Php

http://php.net/var_dump">**var_dump**</a> is for debugging purposes. var_dump always prints the result.

// var_dump(array('', false, 42, array('42')));
array(4) {
  [0]=> string(0) ""
  [1]=> bool(false)
  [2]=> int(42)
  [3]=> array(1) {[0]=>string(2) "42")}
}

http://php.net/print_r">**print_r**</a> is for debugging purposes, too, but does not include the member's type. It's a good idea to use if you know the types of elements in your array, but can be misleading otherwise. print_r by default prints the result, but allows returning as string instead by using the optional $return parameter.

Array (
    [0] =>
    [1] =>
    [2] => 42
    [3] => Array ([0] => 42)
)

http://php.net/manual/en/function.var-export.php">**var_export**</a> prints valid php code. Useful if you calculated some values and want the results as a constant in another script. Note that var_export can not handle reference cycles/recursive arrays, whereas var_dump and print_r check for these. var_export by default prints the result, but allows returning as string instead by using the optional $return parameter.

array (
  0 => '',
  1 => false,
  2 => 42,
  3 => array (0 => '42',),
)

Personally, I think var_export is the best compromise of concise and precise.

Solution 2 - Php

var_dump and var_export relate like this (from the manual)

> var_export() gets structured > information about the given variable. > It is similar to var_dump() with one > exception: the returned representation > is valid PHP code.

They differ from print_r that var_dump exports more information, like the datatype and the size of the elements.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionManish TrivediView Question on Stackoverflow
Solution 1 - PhpphihagView Answer on Stackoverflow
Solution 2 - PhpNanneView Answer on Stackoverflow