What is the difference between print-r(), var_dump(), and var_export() in PHP?
They are mainly used to output a structured view of arrays and objects.
print_r()
Outputting Arrays and Objects for debugging. print_r will output a human-readable format of an array or object. Trying to output it with an echo will throw the error: Notice: Array to string conversion
.
Syntax
print_r(variable, return);
variable
is Required. Specifies the variable to return information about.
return
is Optional. When set to true, this function will return the information (not print it). The default is false.
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'), 'd' => 'dates');
print_r ($a);
The output is:
Array ( [a] => apple [b] => banana [c] => Array ( [0] => x [1] => y [2] => z ) [d] => dates )
var_dump()
Output human-readable debugging information about the content of the argument(s) including its type and value. The var_dump() function is a built-in function of PHP. In the case of a string, it also includes the size of the string passed inside the function. The output is more detailed than print_r because it also outputs the variable type along with its value and other information like object IDs, array sizes, string lengths, reference markers, etc. You can use var_dump to output a more detailed version for debugging. Arrays and objects are explored recursively with values indented to show structure. This function is also effective with expressions.
Syntax
var_dump(var1, var2, ...);
var1
is required.
$a = array ('a' => 'apple', 'b' => 'banana');
$b = 3.1;
$c = true;
$d = 'hello';
var_dump($a,$b, $c, $d);
The output is:
array(2) { ["a"]=> string(5) "apple" ["b"]=> string(6) "banana" }
float(3.1)
bool(true)
string(5) "hello"
var_export()
Output valid PHP Code. It dumps a PHP parseable representation of the item. The var_export() is a built-in function in PHP that is used to return the structured value(information) of a variable that is passed to this function as a parameter. It is similar to var_dump() with one exception: the returned representation is a valid PHP code.
Syntax
var_export(variable_name, set_value)
variable_name
is required.
set_value
is optional. If this parameter is used and set to true var_export() function returns the variable representation instead of outputting it.
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
$c = true;
var_export($c);
$d = 'hello';
var_export($d);
The output is:
array ( 0 => 1, 1 => 2, 2 => array ( 0 => 'a', 1 => 'b', 2 => 'c', ), )
true
'hello'
Note: Variables of type resource couldn't be exported by this function.
Thank you for your time. I hope you found it useful. ❤️
If you enjoyed this article and want to be the first to know when I post a new one, you can follow me on Twitter @habibawael02 or here at Habiba Wael