[print_r()](<http://php.net/manual/en/function.print-r.php>)
- Outputting Arrays and Objects for debugging[print_r](<http://php.net/manual/en/function.print-r.php>)
will output a human readable format of an array or object.
You may have a variable that is an array or object. Trying to output it with an echo
will throw the error:
Notice: Array to string conversion
. You can instead use the print_r
function to dump a human readable format of this variable.
You can pass true as the second parameter to return the content as a string.
$myobject = new stdClass();
$myobject->myvalue = 'Hello World';
$myarray = [ "Hello", "World" ];
$mystring = "Hello World";
$myint = 42;
// Using print_r we can view the data the array holds.
print_r($myobject);
print_r($myarray);
print_r($mystring);
print_r($myint);
This outputs the following:
stdClass Object
(
[myvalue] => Hello World
)
Array
(
[0] => Hello
[1] => World
)
Hello World
42
Further, the output from print_r
can be captured as a string, rather than simply echoed. For instance, the following code will dump the formatted version of $myarray
into a new variable:
$formatted_array = print_r($myarray, true);
Note that if you are viewing the output of PHP in a browser, and it is interpreted as HTML, then the line breaks will not be shown and the output will be much less legible unless you do something like
echo '<pre>' . print_r($myarray, true) . '</pre>';
Opening the source code of a page will also format your variable in the same way without the use of the <pre> tag.
Alternatively you can tell the browser that what you’re outputting is plain text, and not HTML:
header('Content-Type: text/plain; charset=utf-8');
print_r($myarray);
[var_dump()](<http://php.net/manual/en/function.var-dump.php>)
- Output human-readable debugging information about content of the argument(s) including its type and valueThe output is more detailed as compared to print_r
because it also outputs the type of the variable along with its value and other information like object IDs, array sizes, string lengths, reference markers, etc.
You can use [var_dump](<http://php.net/manual/en/function.var-dump.php>)
to output a more detailed version for debugging.
var_dump($myobject, $myarray, $mystring, $myint);