php var_dump() vs print_r()

PhpArrays

Php Problem Overview


What is the difference between var_dump() and print_r() in terms of spitting out an array as string?

Php Solutions


Solution 1 - Php

The var_dump function displays structured information about variables/expressions including its type and value. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references.

The print_r() displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects.

Example:

$obj = (object) array('qualitypoint', 'technologies', 'India');

var_dump($obj) will display below output in the screen.

object(stdClass)#1 (3) {
 [0]=> string(12) "qualitypoint"
 [1]=> string(12) "technologies"
 [2]=> string(5) "India"
}

And, print_r($obj) will display below output in the screen.

stdClass Object ( 
 [0] => qualitypoint
 [1] => technologies
 [2] => India
)

More Info

Solution 2 - Php

Generally, print_r( ) output is nicer, more concise and easier to read, aka more human-readable but cannot show data types.

With print_r() you can also store the output into a variable:

$output = print_r($array, true);

which var_dump() cannot do. Yet var_dump() can show data types.

Solution 3 - Php

var_dump() will show you the type of the thing as well as what's in it.

So you'll get => (string)"var" Example is here.

print_r() will just output the content.

Would output => "var" Example is here.

Solution 4 - Php

If you're asking when you should use what, I generally use print_r() for displaying values and var_dump() for when having issues with variable types.

Solution 5 - Php

var_dump displays structured information about the object / variable. This includes type and values. Like print_r arrays are recursed through and indented.

print_r displays human readable information about the values with a format presenting keys and elements for arrays and objects.

The most important thing to notice is var_dump will output type as well as values while print_r does not.

Solution 6 - Php

It's too simple. The var_dump() function displays structured information about variables/expressions including its type and value. Whereas The print_r() displays information about a variable in a way that's readable by humans.

Example: Say we have got the following array and we want to display its contents.

$arr = array ('xyz', false, true, 99, array('50'));
Array
(
    [0] => xyz
    [1] =>
    [2] => 1
    [3] => 99
    [4] => Array
        (
            [0] => 50
        )
)
var_dump() function - Displays values and types
array(5) {
  [0]=>
  string(3) "xyz"
  [1]=>
  bool(false)
  [2]=>
  bool(true)
  [3]=>
  int(100)
  [4]=>
  array(1) {
    [0]=>
    string(2) "50"
  }
}

For more details: https://stackhowto.com/how-to-display-php-variable-values-with-echo-print_r-and-var_dump/

Solution 7 - Php

Significant differences between var_dump and print_r

both the functions dumps information about the variable, but var_dump multiple parameters which will be dumped, where as print_r can take two parameters out of which first parameter is the variable you want to dump and second is a boolean value.

var_dump can't return any value it can only dump/print the values where as print_r can return the variable information if we set second parameter of print_r to true. The returned value of print_r will be in string format.

The information printed by print_r is much more in readable format where as var_dump prints raw values.

print_r function can be used in many contexts where as var_dump can be used in debugging purposes mainly since it can't return value.

Solution 8 - Php

I'd aditionally recommend putting the output of var_dump() or printr into a pre tag when outputting to a browser.

print "<pre>";
print_r($dataset);
print "</pre>";

Will give a more readable result.

Solution 9 - Php

var_dump($var) shows in-depth details, by providing additional details of

  • data type of the value (including the descendant elements)
  • number of elements in a variable
  • length of the value

Solution 10 - Php

With large arrays, print_r can show far more information than is useful. You can truncate it like this, showing the first 2000 characters or however many you need.

  echo "<pre>" . substr(print_r($dataset, 1), 0, 2000) . "</pre>";

Solution 11 - Php

var_dump() :-

  1. This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
  2. This function display number of element in a variable.
  3. This function display length of variable.
  4. Can't return the value only print the value.
  5. it is use for debugging purpose.

Example :-

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

output :-

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

print_r() :-

  1. Prints human-readable information about a variable.
  2. Not display number of element in a variable as var_dump().
  3. Not display length of variable in a variable as var_dump().
  4. Return the value if we set second parameter to true in printf_r().

Example :-

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

Output:-

<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

Solution 12 - Php

We can pass multiple parameters with var_dump like:

var_dump("array1",$array1,"array2",$array2);

Solution 13 - Php

For all who needs the var_dump() function for testing!
I've written my own test dump function, cause i didn't whant to do that ob_start ... stuff over and over again. The nice thing, it even get's the parameter names from source!

function test_dump (...$params)
{
	
	$file_test_dump = 'test_dump.log';

	$backtrace = debug_backtrace(0, 3);

	$caller_file		= $backtrace[0]['file']);  
	$caller_function 	= $backtrace[1]['function'];
	$caller_line 		= $backtrace[0]['line'];

	if (empty($params))
	{
		file_put_contents ($file_test_dump, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" , FILE_APPEND);
		file_put_contents ($file_test_dump, '!!!!!! ' . date ("[Y-m-d H:i:s:u]", time()) . " - FILE: {$caller_file} | FUNCTION: {$caller_function} | LINE: {$caller_line} !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! \n\n" , FILE_APPEND);
		file_put_contents ($file_test_dump, "!!! No parameter given !!! \n\n" , FILE_APPEND);
		return;
	}
	
	

	// --- get source file ---
	$source_file = file($backtrace[0]['file']);
	
	// --- get line of source file and pre filter with regex ---
	preg_match ('~\(([^*]*)\)~', $source_file [intval($backtrace[0]['line']) - 1], $parameter_line);
 	$parameter_line_filtered = str_replace(" ", "", $parameter_line [1]);

	// put parameter names into array
 	$params_names = explode(',', $parameter_line_filtered);



	// --- OUTPUT	----
	
	file_put_contents ($file_test_dump, "#######################################################################################################################################################################################################################\n" , FILE_APPEND);
	file_put_contents ($file_test_dump, '### ' . date ("[Y-m-d H:i:s:u]", time()) . " - FILE: {$caller_file} | FUNCTION: {$caller_function} | LINE: {$caller_line} ### \n\n" , FILE_APPEND);
	
	
	$i = 0;
	
	foreach ($params as $param)
	{

		$i++;

		file_put_contents ($file_test_dump, "	--- Parameter " . $i . ': ' . $params_names[$i - 1] . " --------------------------------------------------------------------------------------------------------------------------\n", FILE_APPEND);

		if (	is_array($param) 	||
				is_object($param) ||
				is_bool($param)	)
		{
			ob_start();
			var_dump($param);
			file_put_contents ($file_test_dump, ob_get_contents() . "\n\n", FILE_APPEND);
			ob_end_clean();
		}
		else
		{
			file_put_contents ($file_test_dump, $param . "\n\n", FILE_APPEND);
		}


	}

	file_put_contents ($file_test_dump, "\n\n", FILE_APPEND);

}

Solution 14 - Php

print_r() and var_dump() are Array debugging functions used in PHP for debugging purpose. print_r() function returns the array keys and its members as Array([key] = value) whereas var_dump() function returns array list with its array keys with data type and length as well e.g Array(array_length){[0] = string(1)'a'}.

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
QuestioninaView Question on Stackoverflow
Solution 1 - PhpSarfrazView Answer on Stackoverflow
Solution 2 - PhpgilzeroView Answer on Stackoverflow
Solution 3 - PhpDavid YellView Answer on Stackoverflow
Solution 4 - PhpDanny NimmoView Answer on Stackoverflow
Solution 5 - PhpJosh KView Answer on Stackoverflow
Solution 6 - PhpthomasView Answer on Stackoverflow
Solution 7 - PhpAkshay KhaleView Answer on Stackoverflow
Solution 8 - PhpChristian NagelView Answer on Stackoverflow
Solution 9 - Phpʞɔıɥʇɹɐʞ ouɐɯView Answer on Stackoverflow
Solution 10 - PhpNeil BauersView Answer on Stackoverflow
Solution 11 - PhpHeadAndTailView Answer on Stackoverflow
Solution 12 - PhpJasbir RanaView Answer on Stackoverflow
Solution 13 - PhpRegnalfView Answer on Stackoverflow
Solution 14 - PhpMahesh ChaudharyView Answer on Stackoverflow