Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php var_dump() vs print_r()

Tags:

arrays

php

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

like image 994
ina Avatar asked Aug 04 '10 13:08

ina


People also ask

Why Var_dump () is preferable over Print_r ()?

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.

What is difference between Print_r and echo in PHP?

The print and echo are both language constructs to display strings. The echo has a void return type, whereas print has a return value of 1 so it can be used in expressions. The print_r is used to display human-readable information about a variable.

What is the use of Print_r in PHP?

It is a built-in function in print_r in PHP that is used to print or display the contents of a variable. It essentially prints human-readable data about a variable. The value of the variable will be printed if it is a string, integer, or float.

What is the use of Var_dump?

The var_dump() function is used to dump information about a variable. This function displays structured information such as type and value of the given variable. Arrays and objects are explored recursively with values indented to show structure. This function is also effective with expressions.


2 Answers

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

  • var_dump
  • print_r
like image 131
Sarfraz Avatar answered Sep 30 '22 18:09

Sarfraz


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.

like image 37
gilzero Avatar answered Sep 30 '22 18:09

gilzero